752. 打开转盘锁

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

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

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

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/open-the-lock
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

import java.util.*;

class Solution {

    private List<String> next(String str) {
        List<String> ans = new ArrayList<>();
        for (int i = 0; i < str.length(); ++i) {
            char[] chars = str.toCharArray();
            chars[i] = (char) ((str.charAt(i) - '0' + 1) % 10 + '0');
            ans.add(new String(chars));
            chars[i] = (char) ((str.charAt(i) - '0' - 1 + 10) % 10 + '0');
            ans.add(new String(chars));
        }
        return ans;
    }

    public int openLock(String[] deadends, String target) {
        Set<String> visited = new HashSet<>(Arrays.asList(deadends));
        String start = "0000";
        if (visited.contains(start)) {
            return -1;
        }
        Queue<Info> queue = new LinkedList<>();
        visited.add(start);
        queue.offer(new Info(start, 0));
        while (!queue.isEmpty()) {
            Info node = queue.poll();
            if (node.state.equals(target)) {
                return node.step;
            }
            List<String> next = next(node.state);
            for (String str : next) {
                if (!visited.contains(str)) {
                    visited.add(str);
                    queue.offer(new Info(str, node.step + 1));
                }
            }
        }
        return -1;
    }
}

class Info {
    String state;
    int step;

    public Info(String state, int step) {
        this.state = state;
        this.step = step;
    }
}
posted @ 2022-01-19 15:41  Tianyiya  阅读(85)  评论(0)    收藏  举报