# 打开转盘锁（leetcode）BFS解法

## 打开转盘锁（leetcode）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
// 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) {
}
remove the first node from queue;
}
}
return -1;          // there is no path from root to target
}
``````

——————————AC代码——————————

``````class Solution {
public:
int openLock( vector<string> &deadends, string target ) {
//这里visited要用set容器，原因有二
//原因1：set容器find函数查找速度快，不易时间超限，他按二叉树存储，且插入时自动排序
//原因2：set容器自带查找函数find，不用我们自己再写

for( int i = 0; i < deadends.size(); i++ ) {
}

//find函数找到的话返回元素的迭代器，未找到的话返回end
set<string>::iterator pos = visited.find( "0000" );

if( pos != visited.end() ) {
return -1; //说明元素已经访问过了，直接return
}

visited.insert( "0000" );
queue<string> q;
int count = 0;	//记录树的层数
q.push( "0000" );

//参考模板
while( !q.empty() ) {
int size = q.size();

for( int i = 0; i < size; i++ ) {
string front = q.front();	//队列的头元素
q.pop();

if( front == target ) {
return count;	//找到了目标元素，返回count
}

//j从0到3，代表4位密码的0-3位，每位上都有加减两种操作
for( int j = 0; j < 4; j++ ) {

set<string>::iterator s = visited.find( addTemp );

//此密码以前未访问过
if( s == visited.end() ) {
}

string subtractTemp = codeSubstact( front, j );

s = visited.find( subtractTemp );

if( s == visited.end() ) {
q.push( subtractTemp );
visited.insert( subtractTemp );
}
}
}

count++;	//搜索玩一次，树的层次加1
}

return -1;	//如果能找到的话肯定已经返回了，到不了这一步，到这肯定没找到，返回-1
}

//向上拨动密码，执行类似加的操作
string codeAdd( string s, int i ) {
//当密码位是9时，再往上就是0
if( s[i] == '9' ) {
s[i] -= 9;	//等同于s[i]='0'
} else {
s[i] += 1;
}

return s;
}

//向下拨动密码，执行类似减的操作
string codeSubstact( string s, int i ) {
//当密码位是0时，再往下就是9
if( s[i] == '0' ) {
s[i] += 9;	//等同于s[i]='9'
} else {
s[i] -= 1;
}

return s;
}
};
``````

原文作者：x-robot
原文地址: https://blog.csdn.net/elexiangchirou/article/details/121113500
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。