DFS和BFS相关算法

题目: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;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值