【发布时间】:2020-08-17 00:18:34
【问题描述】:
我刚刚学习了BFS算法,我在这里尝试应用BFS算法解决leetcode问题Open the Lock
我的算法适用于某些用例,而对其他用例输出错误的答案。谁能帮我理解我错过了什么?
提前致谢
class Solution {
Queue<String> queue = new LinkedList<String>();
HashSet<String> deads = new HashSet<String>();
public int openLock(String[] deadends, String target) {
for(int i = 0; i < deadends.length; i++){
deads.add(deadends[i]);
}
if(deads.contains("0000"))return -1;
int level = bfs("0000", target);
return level;
}
public int bfs(String start, String target){
int level = 0;
queue.add(start); // add the start to the queue
deads.add(start);
while(!queue.isEmpty()){
int groupSize = queue.size();
while(groupSize >0){
String current = queue.poll();
if(current.equals(target)) return level;
for(int i = 0; i < current.length(); i++){
char c = current.charAt(i);
char temp = c;
if( c == '9'){
c = '0';
temp = c;
}else{
c++;
}
String upString = current.substring(0, i) + c + current.substring(i + 1);
if(!deads.contains(upString)){
queue.add(upString);
deads.add(upString);
}
c = temp;
if( c == '0'){
c = '9';
}
else{
c--;
}
String downString = current.substring(0, i) + c + current.substring(i + 1);
if(!deads.contains(downString)){
queue.add(downString);
deads.add(downString);
}
}
groupSize = groupSize - 1;
}
level = level + 1;
}
return -1;
}
}
【问题讨论】:
标签: java algorithm queue breadth-first-search