题目:752. 打开转盘锁
1.分析出是个N叉数的问题
2.广度优先搜索求最短路径
3.BFS 非递归写法的level 计数
class Solution {
public int openLock(String[] deadends, String target) {
Set<String> set = new HashSet<>(Arrays.asList(deadends));
Set<String> visited = new HashSet<>();
Queue<String> queue = new LinkedList<>();
int level = 0;
String startStr = "0000";
if(set.contains(startStr)) return -1;
queue.offer(startStr);
visited.add(startStr);
while(!queue.isEmpty()){
int size = queue.size();
while(size-- >0){
String str = queue.poll();
if(str.equals(target)) return level;
for(int i=0;i<4;++i){
char ch = str.charAt(i);
String strAdd = str.substring(0,i)+(ch =='9'?0:ch-'0'+1)+str.substring(i+1);
String strSub = str.substring(0,i)+(ch =='0'?9:ch-'0'-1)+str.substring(i+1);
if(!visited.contains(strAdd)&&!set.contains(strAdd)){
queue.offer(strAdd);
visited.add(strAdd);
}
if(!visited.contains(strSub)&&!set.contains(strSub)){
queue.offer(strSub);
visited.add(strSub);
}
}
}
level++;
}
return -1;
}
}
279. 完全平方数
1.N叉树的层次遍历
class Solution {
public int numSquares(int n) {
Queue<Integer> queue =new LinkedList<>();
Set<Integer> visited = new HashSet<>();
queue.offer(0);
visited.add(0);
int level = 0;
while(!queue.isEmpty()){
int size = queue.size();
level++;
for(int i=0;i<size;++i){
int digit = queue.poll();
for(int j = 1;j<n;++j){
int s = digit+j*j;
if( s== n) return level;
else if(s > n) break;
else{
if(!visited.contains(s)){
queue.offer(s);
visited.add(s);
}
}
}
}
}
return level;
}
}