Skip to content

752. Open the Lock 👍

  • Time: $O(10^4)$
  • Space: $O(10^4)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
class Solution {
 public:
  int openLock(vector<string>& deadends, string target) {
    unordered_set<string> seen{deadends.begin(), deadends.end()};
    if (seen.contains("0000"))
      return -1;
    if (target == "0000")
      return 0;

    queue<string> q{{"0000"}};

    for (int step = 1; !q.empty(); ++step)
      for (int sz = q.size(); sz > 0; --sz) {
        string word = q.front();
        q.pop();
        for (int i = 0; i < 4; ++i) {
          const char cache = word[i];
          // Increase the i-th digit by 1.
          word[i] = word[i] == '9' ? '0' : word[i] + 1;
          if (word == target)
            return step;
          if (!seen.contains(word)) {
            q.push(word);
            seen.insert(word);
          }
          word[i] = cache;
          // Decrease the i-th digit by 1.
          word[i] = word[i] == '0' ? '9' : word[i] - 1;
          if (word == target)
            return step;
          if (!seen.contains(word)) {
            q.push(word);
            seen.insert(word);
          }
          word[i] = cache;
        }
      }

    return -1;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
class Solution {
  public int openLock(String[] deadends, String target) {
    Set<String> seen = new HashSet<>(Arrays.asList(deadends));
    if (seen.contains("0000"))
      return -1;
    if (target.equals("0000"))
      return 0;

    Queue<String> q = new ArrayDeque<>(List.of("0000"));

    for (int step = 1; !q.isEmpty(); ++step)
      for (int sz = q.size(); sz > 0; --sz) {
        StringBuilder sb = new StringBuilder(q.poll());
        for (int i = 0; i < 4; ++i) {
          final char cache = sb.charAt(i);
          // Increase the i-th digit by 1.
          sb.setCharAt(i, sb.charAt(i) == '9' ? '0' : (char) (sb.charAt(i) + 1));
          String word = sb.toString();
          if (word.equals(target))
            return step;
          if (!seen.contains(word)) {
            q.offer(word);
            seen.add(word);
          }
          sb.setCharAt(i, cache);
          // Decrease the i-th digit by 1.
          sb.setCharAt(i, sb.charAt(i) == '0' ? '9' : (char) (sb.charAt(i) - 1));
          word = sb.toString();
          if (word.equals(target))
            return step;
          if (!seen.contains(word)) {
            q.offer(word);
            seen.add(word);
          }
          sb.setCharAt(i, cache);
        }
      }

    return -1;
  }
}