Leetcode 752. 打开转盘锁 题解

题目链接:https://leetcode-cn.com/problems/open-the-lock/
Leetcode 752. 打开转盘锁 题解_第1张图片
Leetcode 752. 打开转盘锁 题解_第2张图片
字符串转换成0-10000内的数字记录状态。

写两个函数next和last得到变换后的状态。

deadend中的小可爱们标记状态不可访问即可。

代码如下:

class Solution {
public:
    bool vis[10000];
    int a[4];

    int trans(string s) {
        int res = 0;
        for(int i = 0; i < s.size(); i++) {
            res = res * 10 + s[i] - '0';
        }
        return res;
    }

    int next(int num, int pos) {
        a[0] = num / 1000;
        a[1] = num / 100 - a[0] * 10;
        a[3] = num % 10;
        a[2] = (num % 100 - a[3]) / 10;
        if(a[pos] == 9) {
            a[pos] = 0;
        } else {
            a[pos]++;
        }
        return a[0] * 1000 + a[1] * 100 + a[2] * 10 + a[3];
    }

    int last(int num, int pos) {
        a[0] = num / 1000;
        a[1] = num / 100 - a[0] * 10;
        a[3] = num % 10;
        a[2] = (num % 100 - a[3]) / 10;
        if(a[pos] == 0) {
            a[pos] = 9;
        } else {
            a[pos]--;
        }
        return a[0] * 1000 + a[1] * 100 + a[2] * 10 + a[3];
    }

    int openLock(vector<string>& deadends, string target) {
        for(int i = 0; i < deadends.size(); i++) {
            vis[trans(deadends[i])] = true;
        }
        if(vis[0]) {
            return -1;
        }
        int tar = trans(target);
        int res = 0;
        queue<int> q;
        q.push(0);
        while(!q.empty()) {
            int len = q.size();
            while(len--) {
                int now = q.front();
                //printf("now = %d, res = %d\n", now, res);
                q.pop();
                if(now == tar) {
                    return res;
                }
                for(int i = 0; i < 4; i++) {
                    if(!vis[next(now, i)]) {
                        vis[next(now, i)] = true;
                        q.push(next(now, i));
                    }
                    if(!vis[last(now, i)]) {
                        vis[last(now, i)] = true;
                        q.push(last(now, i));
                    }
                }
            }
            
            
            res++;
        }
        return -1;
    }
};

你可能感兴趣的:(Leetcode,DFS_BFS)