LeetCode 752. 打开转盘锁(Java代码)

https://leetcode-cn.com/problems/open-the-lock/

题目描述

一个转盘有四位数字,范围是0~9 。并且扭动的时候非常自由,可以从0到9 也可以从9到0。 现在密码是 target “xxxx”,请问从"0000"开始至少需要多少次旋转可以得到target,其中必须避开 列表 deadends

输入输出样例

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

题解

使用广度优先搜索策略,将每一次的8种选择都添加进队列中

class Solution {
    public int openLock(String[] deadends, String target) {
        // 将deadend中的所有值都添加到 哈希表中
        Set<String> dead = new HashSet<String>();
        for(String str:deadends){
            dead.add(str);
        }
              
        // 每个字符有两个旋转方向,一共可以旋转8个方向
        Queue<String> queue = new LinkedList<String>();
        // 存储已经出现过的情况
        Set<String> seen = new HashSet<String>();
        queue.add("0000");
        seen.add("0000");
        int count = 0;
        while(!queue.isEmpty()){
            int size = queue.size();
            while(size-- > 0){
                String str = queue.poll();
                seen.add(str);
                if(str.equals(target)) return count;
                else if(!dead.contains(str)){
                    for(int i=0; i<4; i++){
                        for(int add = -1; add <= 1; add += 2){
                            // 得到转动后的值
                            int temp = (str.charAt(i) - '0' + add + 10) % 10;
                            String next = str.substring(0,i) + (""+temp) + str.substring(i+1);
                            if(!seen.contains(next)){
                                queue.offer(next);
                                seen.add(next);
                            }
                        }
                    }
                }
            }
            count++;
        }
        
        return -1;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值