https://leetcode.com/contest/weekly-contest-64/problems/open-the-lock/

class Solution {
public:
    int openLock(vector<string>& deadends, string target) {
        map<string, int> m; 
        map<string, int>::iterator mit;
        for (int i = 0; i < deadends.size(); i++) {
            m.insert(make_pair(deadends[i], -1));
        }
        queue<pair<string, int> > q;

        string s("0000");
        if (m.find(s) != m.end()) {
            return -1;
        }
        q.push(make_pair(s, 0));
        m.insert(make_pair(s, 0));
        while(!q.empty()) {
            string now    = q.front().first; 
            int    length = q.front().second;
            //printf("%s %d\n", now.c_str(), length);
            q.pop();
            for (int i = 0; i < 4; i++) {
                string up(now);
                char c = up.at(i);
                if (c < '9') {
                    c = c + 1;
                } else {
                    c = '0';
                }
                up.erase(i, 1);
                up.insert(i, 1, c);
                mit = m.find(up);
                //printf("    u %s %d\n", up.c_str(), mit == m.end());
                if (mit == m.end()) {
                    if(!target.compare(up)) {
                        //printf("    ans %d\n", length + 1);
                        return length + 1;
                    }
                    q.push(make_pair(up, (length + 1)));
                    m.insert(make_pair(up, (length + 1)));
                }

                string down(now);
                c = down.at(i);
                if (c > '0') {
                    c = c - 1;
                } else {
                    c = '9';
                }
                down.erase(i, 1);
                down.insert(i, 1, c);
                mit = m.find(down);
                //printf("    d %s %d\n", down.c_str(), mit == m.end());
                if (mit == m.end()) {
                    if(!target.compare(down)) {
                        //printf("    ans %d\n", length + 1);
                        return length + 1;
                    }
                    q.push(make_pair(down, (length + 1)));
                    m.insert(make_pair(down, (length + 1)));
                }
            }
        }
        return -1;
    }
};

留言

這個網誌中的熱門文章

https://leetcode.com/contest/leetcode-weekly-contest-52/problems/longest-univalue-path/

https://leetcode.com/contest/leetcode-weekly-contest-52/problems/maximum-sum-of-3-non-overlapping-subarrays/