leetcode752. 打开转盘锁(bfs)

你有一个带有四个圆形拨轮的转盘锁。每个拨轮都有10个数字: ‘0’, ‘1’, ‘2’, ‘3’, ‘4’, ‘5’, ‘6’, ‘7’, ‘8’, ‘9’ 。每个拨轮可以自由旋转:例如把 ‘9’ 变为 ‘0’,‘0’ 变为 ‘9’ 。每次旋转都只能旋转一个拨轮的一位数字。

锁的初始数字为 ‘0000’ ,一个代表四个拨轮的数字的字符串。

列表 deadends 包含了一组死亡数字,一旦拨轮的数字和列表里的任何一个元素相同,这个锁将会被永久锁定,无法再被旋转。

字符串 target 代表可以解锁的数字,你需要给出最小的旋转次数,如果无论如何不能解锁,返回 -1。

示例 1:

输入:deadends = [“0201”,“0101”,“0102”,“1212”,“2002”], target = “0202”
输出:6
解释:
可能的移动序列为 “0000” -> “1000” -> “1100” -> “1200” -> “1201” -> “1202” -> “0202”。
注意 “0000” -> “0001” -> “0002” -> “0102” -> “0202” 这样的序列是不能解锁的,
因为当拨动到 “0102” 时这个锁就会被锁定。

代码

class Solution {
    public int openLock(String[] deadends, String target) {

        StringBuilder stringBuilder=new StringBuilder();
        HashSet<String> hashSet=new HashSet<>();
        for(String s:deadends) hashSet.add(s);
          if(hashSet.contains("0000")) return -1;//起点就锁住了
        Queue<String> queue=new LinkedList<>();
        queue.add("0000");
        HashSet<String> check=new HashSet<>();//记录以及访问过的字符串
        check.add("0000");
        int res=0;
        while (!queue.isEmpty())
        {
            int size=queue.size();
            for(int j=0;j<size;j++)
            {
                String cur=queue.poll();

                for(int i=0;i<4;i++)//4个位置变化
                {
                    stringBuilder=new StringBuilder(cur);
                    char na=(char)(stringBuilder.charAt(i)+1),ns=(char)(stringBuilder.charAt(i)-1);//当前位置加一或减一
                    if(na>'9') na='0'; else if(ns<'0') ns='9';
                    stringBuilder.setCharAt(i,na);
                    String temp=stringBuilder.toString();
                    if(temp.equals(target)) return res+1;//找到了目标
                    if(!hashSet.contains(temp)&&!check.contains(temp))//看看当前字符串有没有被锁或者被访问过了
                    {
                        queue.offer(temp);
                        check.add(temp);
                    }

                    stringBuilder.setCharAt(i,ns);
                     temp=stringBuilder.toString();
                    if(temp.equals(target)) return res+1;
                    if(!hashSet.contains(temp)&&!check.contains(temp))
                    {
                        queue.offer(temp);
                        check.add(temp);
                    }
                }

            }
            res++;
        }
        return -1;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_44560620/article/details/107684480