力扣labuladong——一刷day08

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

文章目录

  • 前言
  • 一、力扣111. 二叉树的最小深度
  • 二、力扣752. 打开转盘锁


前言


一、力扣111. 二叉树的最小深度

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public int minDepth(TreeNode root) {
        if(root == null)return 0;
        Deque<TreeNode> deq = new ArrayDeque<>();
        deq.offerLast(root);
        int level = 0;
        while(!deq.isEmpty()){
            int size = deq.size();
            level ++;
            for(int i = 0; i < size; i ++){
                TreeNode temp = deq.pollFirst();
                if(temp.left == null && temp.right == null){
                    return level;
                }
                if(temp.left != null){
                    deq.offerLast(temp.left);
                }
                if(temp.right != null){
                    deq.offerLast(temp.right);
                }
            }
        }
        return level;
    }
}

二、力扣752. 打开转盘锁

class Solution {
    public int openLock(String[] deadends, String target) {
        Deque<String> deq = new ArrayDeque<>();
        Set<String> set = new HashSet<>();
        Set<String> set1 = new HashSet<>();
        for(String s : deadends){
            set1.add(s);
        }
        deq.offerLast("0000");
        set.add("0000");
        int step = 0;
        while(!deq.isEmpty()){
            int size = deq.size();
            for(int i = 0; i < size; i ++){
                String cur = deq.pollFirst();
                if(set1.contains(cur)){
                    continue;
                }
                if(target.equals(cur)){
                    return step;
                }
                for(int j = 0; j < 4; j ++){
                    String s1 = fun1(cur,j);
                    if(!set.contains(s1)){
                        deq.offerLast(s1);
                        set.add(s1);    
                    }
                    String s2 = fun2(cur,j);
                    if(!set.contains(s2)){
                        deq.offerLast(s2);
                        set.add(s2);
                    }
                }
            }
            // System.out.println(step);
            step ++;
        }
        return -1;
    }
    public String fun1(String s,int i){
        char[] ch = s.toCharArray();
        if(ch[i] == '9'){
            ch[i] = '0';
        }else{
            ch[i] += 1;
        }
        return new String(ch);
    }
    public String fun2(String s, int i){
        char[] ch = s.toCharArray();
        if(ch[i] == '0'){
            ch[i] = '9';
        }else{
            ch[i] -= 1;
        }
        return new String(ch);
    }
}

你可能感兴趣的:(leetcode,算法,职场和发展,java)