752. Open the Lock

这题也是基本BFS
没什么好说的,
注意在把“0000”放进去的时候要判断corner case,
他本身是不是一个deadend, 他本身是不是target什么的 。

class Solution {
    public int openLock(String[] deadends, String target) {
        Set visited = new HashSet<>();
        
        
        Set dead = new HashSet<>();
        for (String end : deadends) {
            dead.add(end);
        }
        if (dead.contains("0000")) return -1;
        if ("0000".equals(target)) return 0;
        visited.add("0000");
        Queue queue = new LinkedList<>();
        queue.add("0000");
        int level = 0;
        
        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                String cur = queue.poll();
                for (String next : genNext(cur)) {
                    if (visited.contains(next) || 
                       dead.contains(next)) continue;
                    if (next.equals(target)) return level + 1;
                    queue.offer(next);
                    visited.add(next);
                }
            }
            level++;
        }
        return -1;
    }
    private List genNext(String cur) {
        char[] array = cur.toCharArray();
        List ans = new ArrayList<>();
        for (int i = 0; i < 4; i++) {
            if (array[i] != '9' && array[i] != '0') {
                array[i] += 1;
                ans.add(new String(array));
                array[i] -= 2;
                ans.add(new String(array));
                array[i] += 1;
            } else if (array[i] == '9') {
                array[i] = '8';
                ans.add(new String(array));
                array[i] = '0';
                ans.add(new String(array));
                array[i] = '9';
            } else if (array[i] == '0') {
                array[i] = '9';
                ans.add(new String(array));
                array[i] = '1';
                ans.add(new String(array));
                array[i] = '0';
            }
        }
        return ans;
    }
}

你可能感兴趣的:(752. Open the Lock)