• [LeetCode] 752. Open the Lock 开锁


    You have a lock in front of you with 4 circular wheels. Each wheel has 10 slots: '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'. The wheels can rotate freely and wrap around: for example we can turn '9' to be '0', or '0' to be '9'. Each move consists of turning one wheel one slot.

    The lock initially starts at '0000', a string representing the state of the 4 wheels.

    You are given a list of deadends dead ends, meaning if the lock displays any of these codes, the wheels of the lock will stop turning and you will be unable to open it.

    Given a target representing the value of the wheels that will unlock the lock, return the minimum total number of turns required to open the lock, or -1 if it is impossible.

    Example 1:

    Input: deadends = ["0201","0101","0102","1212","2002"], target = "0202"
    Output: 6
    Explanation:
    A sequence of valid moves would be "0000" -> "1000" -> "1100" -> "1200" -> "1201" -> "1202" -> "0202".
    Note that a sequence like "0000" -> "0001" -> "0002" -> "0102" -> "0202" would be invalid,
    because the wheels of the lock become stuck after the display becomes the dead end "0102". 

    Example 2:

    Input: deadends = ["8888"], target = "0009"
    Output: 1
    Explanation:
    We can turn the last wheel in reverse to move from "0000" -> "0009".

    Example 3:

    Input: deadends = ["8887","8889","8878","8898","8788","8988","7888","9888"], target = "8888"
    Output: -1
    Explanation:
    We can't reach the target without getting stuck.

    Example 4:

    Input: deadends = ["0000"], target = "8888"
    Output: -1

    Note:

    1. The length of deadends will be in the range [1, 500].
    2. target will not be in the list deadends.
    3. Every string in deadends and the string target will be a string of 4 digits from the 10,000 possibilities '0000' to '9999'.

    Hint:

    We can think of this problem as a shortest path problem on a graph: there are `10000` nodes (strings `'0000'` to `'9999'`), and there is an edge between two nodes if they differ in one digit, that digit differs by 1 (wrapping around, so `'0'` and `'9'` differ by 1), and if *both* nodes are not in `deadends`.

    有一个可转动的四位数的密码锁,给一个目标值,还有一些锁死的情况,出现死锁的位置,就不能再动了,相当于迷宫中的障碍物。问最少多少步可以从初始的0000位置转动到给定的target位置。

    可以把问题想成图的最短路径问题,有10000个节点(字符串‘0000'到'9999'),如果两个节点之间相差1并且不在锁死节点中,则它们之间有一个边。类似于迷宫遍历的问题,只不过相邻位置不再是上下左右四个位置,而是四位数字每个都加一减一,总共有八个相邻的位置。

    解法:BFS

    Java:

    public static int openLock(String[] deadends, String target) {
            Queue<String> q = new LinkedList<>();
            Set<String> deads = new HashSet<>(Arrays.asList(deadends));
            Set<String> visited = new HashSet<>();
    
            int depth = 0;
            String marker = "*";
            q.addAll(Arrays.asList("0000", "*"));
            while(!q.isEmpty()) {
                String node = q.poll();
                if(node.equals(target))
                    return depth;
                if(visited.contains(node) || deads.contains(node))
                    continue;
                if(node.equals(marker) && q.isEmpty())
                    return -1;
                if(node.equals(marker)) {
                    q.add(marker);
                    depth += 1;
                } else {
                    visited.add(node);
                    q.addAll(getSuccessors(node));
                }
            }
            return depth;
        }
    
        private static List<String> getSuccessors(String str) {
            List<String> res = new LinkedList<>();
            for (int i = 0; i < str.length(); i++) {
                res.add(str.substring(0, i) + (str.charAt(i) == '0' ? 9 :  str.charAt(i) - '0' - 1) + str.substring(i+1));
                res.add(str.substring(0, i) + (str.charAt(i) == '9' ? 0 :  str.charAt(i) - '0' + 1) + str.substring(i+1));
            }
            return res;
        }  

    Python: 

    Shortest path finding, when the weights are constant, as in this case = 1, BFS is the best way to go.

    Best way to avoid TLE is by using deque and popleft() .
    [Using list() and pop(0) is a linear operation in Python, resulting in TLE]

    class Solution(object):
        def openLock(self, deadends, target):
            """
            :type deadends: List[str]
            :type target: str
            :rtype: int
            """
            marker, depth = 'x', 0
            visited, q, deadends = set(), deque(['0000', marker]), set(deadends)
    
            while q:
                node = q.popleft()
                if node == target:
                    return depth
                if node in visited or node in deadends:
                    continue
                if node == marker and not q:
                    return -1
                if node == marker:
                    q.append(marker)
                    depth += 1
                else:
                    visited.add(node)
                    q.extend(self.successors(node))
            return -1
    
        def successors(self, src):
            res = []
            for i, ch in enumerate(src):
                num = int(ch)
                res.append(src[:i] + str((num - 1) % 10) + src[i+1:])
                res.append(src[:i] + str((num + 1) % 10) + src[i+1:])
            return res  

    Python:

    # Time:  O(k * n^k + d), n is the number of alphabets,
    #                        k is the length of target,
    #                        d is the size of deadends
    # Space: O(k * n^k + d)
    class Solution(object):
        def openLock(self, deadends, target):
            """
            :type deadends: List[str]
            :type target: str
            :rtype: int
            """
            dead = set(deadends)
            q = ["0000"]
            lookup = {"0000"}
            depth = 0
            while q:
                next_q = []
                for node in q:
                    if node == target: return depth
                    if node in dead: continue
                    for i in xrange(4):
                        n = int(node[i])
                        for d in (-1, 1):
                            nn = (n+d) % 10
                            neighbor = node[:i] + str(nn) + node[i+1:]
                            if neighbor not in lookup:
                                lookup.add(neighbor)
                                next_q.append(neighbor)
                q, next_q = next_q, []
                depth += 1
            return -1  

    C++:

    class Solution {
    public:
        int openLock(vector<string>& deadends, string target) {
            unordered_set<string> deadlock(deadends.begin(), deadends.end());
            if (deadlock.count("0000")) return -1;
            int res = 0;
            unordered_set<string> visited{{"0000"}};
            queue<string> q{{"0000"}};
            while (!q.empty()) {
                ++res;
                for (int k = q.size(); k > 0; --k) {
                    auto t = q.front(); q.pop();
                    for (int i = 0; i < t.size(); ++i) {
                        for (int j = -1; j <= 1; ++j) {
                            if (j == 0) continue;
                            string str = t;
                            str[i] = ((t[i] - '0') + 10 + j) % 10 + '0';
                            if (str == target) return res;
                            if (!visited.count(str) && !deadlock.count(str)) q.push(str);        
                            visited.insert(str);
                        }
                    }
                }
            }
            return -1;
        }
    };
    

    C++:  

    class Solution {
    public:
        int openLock(vector<string>& deadends, string target) {
            unordered_set<string> deadlock(deadends.begin(), deadends.end());
            if (deadlock.count("0000")) return -1;
            int res = 0;
            unordered_set<string> visited{{"0000"}};
            queue<string> q{{"0000"}};
            while (!q.empty()) {
                ++res;
                for (int k = q.size(); k > 0; --k) {
                    auto t = q.front(); q.pop();
                    for (int i = 0; i < t.size(); ++i) {
                        char c = t[i];
                        string str1 = t.substr(0, i) + to_string(c == '9' ? 0 : c - '0' + 1) + t.substr(i + 1);
                        string str2 = t.substr(0, i) + to_string(c == '0' ? 9 : c - '0' - 1) + t.substr(i + 1);
                        if (str1 == target || str2 == target) return res;
                        if (!visited.count(str1) && !deadlock.count(str1)) q.push(str1);
                        if (!visited.count(str2) && !deadlock.count(str2)) q.push(str2);
                        visited.insert(str1);
                        visited.insert(str2);
                    }
                }
            }
            return -1;
        }
    };
    

      

    All LeetCode Questions List 题目汇总

  • 相关阅读:
    误报的java.sql.SQLException: Parameter number 21 is not an OUT parameter
    mysql bin-log和innodb_log的关系
    线上mysql内存持续增长直至内存溢出被killed分析(已解决)
    mysql服务器io等待高定位与分析
    mysql 5.6到percona 5.6小版本升级
    mysql内存消耗分析
    centos 7安装mysql报错-bash: ./scripts/mysql_install_db: /usr/bin/perl: bad interpreter: No such file or directory
    windows 7文件误删shift+delete后找回
    oschina github使用指南
    couchbase单向同步
  • 原文地址:https://www.cnblogs.com/lightwindy/p/9847658.html
Copyright © 2020-2023  润新知