BFS解开行李箱密码锁
题目:有一个带有四个圆形拨轮的转盘锁,每个拨轮都有0-9一共10个数字。每个拨轮可以上下旋转:例如把9变成0,或者0变成9,每次旋转只能将一个拨轮旋转一下。转盘锁的四个拨轮初始都是0,用字符串"0000"表示。现在给定输入一个列表deadends和一个字符串target,其中taeget代表可以打开密码锁的数字,而deadends中包含了一组死亡数字,要避免拨出其中的任何一个密码。请写出一个算法,计算从初始状态"0000"拨出target的最少次数,如果永远无法拨出target,则返回一个-1。
#include <iostream> #include <queue> #include <unordered_set> #include <string> using namespace std; class Solution { public: string plus_one(string str, int index)//str数组里面的第index个数据向上拨一下 { if (str[index] == '9') { str[index] = '0'; } else { str[index] = str[index] + 1; } return str; } string down_one(string str, int index) { if (str[index] == '0') { str[index] = '9'; } else { str[index] = str[index] - 1; } return str; } int openLock(vector<string>& deadends, string target) { int step = 0; unordered_set<string> deadset(deadends.begin(), deadends.end()); queue<string> lockQueue; lockQueue.push("0000"); unordered_set<string> visited; visited.insert("0000"); while (!lockQueue.empty()) { int sz = lockQueue.size(); for (int i = 0; i < sz; i++) { string node = lockQueue.front(); lockQueue.pop(); if (deadset.find(node) != deadset.end()) continue; if (node.compare(target) == 0)//如果遇到了直接返回步骤数目 return step; for (int j = 0; j < 4; j++) { string up = plus_one(node, j);//向上得到的结果 //如果这个结果不在visited里面就加入,同时放到队列 if (visited.count(up) <= 0) { visited.insert(up); lockQueue.push(up); } string down = down_one(node, j); if (visited.count(down) <= 0) { visited.insert(down); lockQueue.push(down); } } } step++; } return -1; } }; int main() { vector<string> dead = { "0201", "0101", "0102", "1212", "2002" }; string target("0202"); Solution s; int step = s.openLock(dead, target); cout << step << endl; return 0; }

浙公网安备 33010602011771号