Leetcode 752打開轉盤鎖

題目
你有一個帶有四個圓形撥輪的轉盤鎖。每個撥輪都有10個數字: ‘0’, ‘1’, ‘2’, ‘3’, ‘4’, ‘5’, ‘6’, ‘7’, ‘8’, ‘9’ 。每個撥輪可以自由旋轉:例如把 ‘9’ 變爲 ‘0’,‘0’ 變爲 ‘9’ 。每次旋轉都只能旋轉一個撥輪的一位數字。
鎖的初始數字爲 ‘0000’ ,一個代表四個撥輪的數字的字符串。
列表 deadends 包含了一組死亡數字,一旦撥輪的數字和列表裏的任何一個元素相同,這個鎖將會被永久鎖定,無法再被旋轉。
字符串 target 代表可以解鎖的數字,你需要給出最小的旋轉次數,如果無論如何不能解鎖,返回 -1。
示例 1:
輸入:deadends = [“0201”,“0101”,“0102”,“1212”,“2002”], target = “0202”
輸出:6
解釋:
可能的移動序列爲 “0000” -> “1000” -> “1100” -> “1200” -> “1201” -> “1202” -> “0202”。
注意 “0000” -> “0001” -> “0002” -> “0102” -> “0202” 這樣的序列是不能解鎖的,
因爲當撥動到 “0102” 時這個鎖就會被鎖定。
示例 2:
輸入: deadends = [“8888”], target = “0009”
輸出:1
解釋:
把最後一位反向旋轉一次即可 “0000” -> “0009”。
示例 3:
輸入: deadends = [“8887”,“8889”,“8878”,“8898”,“8788”,“8988”,“7888”,“9888”], target = “8888”
輸出:-1
解釋:
無法旋轉到目標數字且不被鎖定。
示例 4:
輸入: deadends = [“0000”], target = “8888”
輸出:-1
提示:
死亡列表 deadends 的長度範圍爲 [1, 500]。
目標數字 target 不會在 deadends 之中。
每個 deadends 和 target 中的字符串的數字會在 10,000 個可能的情況 ‘0000’ 到 ‘9999’ 中產生。

結題思路
廣度優先搜索(BFS)的一個常見應用是找出從根結點到目標結點的最短路徑。在本文中,我們提供了一個示例來解釋在 BFS 算法中是如何逐步應用隊列的。
BFS的僞代碼

/*
 * Return the length of the shortest path between root and target node.
 */
int BFS(Node root, Node target) {
    Queue<Node> queue;  // store all nodes which are waiting to be processed
    int step = 0;       // number of steps neeeded from root to current node
    // initialize
    add root to queue;
    // BFS
    while (queue is not empty) {
        step = step + 1;
        // iterate the nodes which are already in the queue
        int size = queue.size();
        for (int i = 0; i < size; ++i) {
            Node cur = the first node in queue;
            return step if cur is target;
            for (Node next : the neighbors of cur) {
                add next to queue;
            }
            remove the first node from queue;
        }
    }
    return -1;          // there is no path from root to target
}

解題代碼
class Solution {
public:
int openLock(vector& deadends, string target) {
unordered_set deadlocks(deadends.begin(),deadends.end());
if(deadlocks.count(target)!=0 || deadlocks.count(“0000”)!=0) return -1;
queue q;
q.push(“0000”);
unordered_set visited;
visited.insert(“0000”);
vector directs={-1,1};
int res=0;
while(!q.empty()){
int size=q.size();
while(size–>0){
auto t=q.front();
q.pop();
if(t==target) return res;
if(deadlocks.count(t)) return -1;
for(int i=0;i<t.size();i++){
for(auto direct:directs){
string newWord=t;
newWord[i]=(newWord[i]-‘0’+10+direct)%10+‘0’;
if(visited.count(newWord) || deadlocks.count(newWord)) continue;
q.push(newWord);
visited.insert(newWord);
}
}
}
res++;
}
return -1;
}
};

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章