LeetCode Solutions

752. Open the Lock

Time: $O(10^4)$

Space: $O(10^4)$

			

class Solution {
 public:
  int openLock(vector<string>& deadends, string target) {
    unordered_set<string> seen{begin(deadends), end(deadends)};
    if (seen.count("0000"))
      return -1;
    if (target == "0000")
      return 0;

    int ans = 0;
    queue<string> q{{"0000"}};

    while (!q.empty()) {
      ++ans;
      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 i-th digit by 1
          word[i] = word[i] == '9' ? '0' : word[i] + 1;
          if (word == target)
            return ans;
          if (!seen.count(word)) {
            q.push(word);
            seen.insert(word);
          }
          word[i] = cache;
          // Decrease i-th digit by 1
          word[i] = word[i] == '0' ? '9' : word[i] - 1;
          if (word == target)
            return ans;
          if (!seen.count(word)) {
            q.push(word);
            seen.insert(word);
          }
          word[i] = cache;
        }
      }
    }

    return -1;
  }
};
			

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;

    int ans = 0;
    Queue<String> q = new ArrayDeque<>(Arrays.asList("0000"));

    while (!q.isEmpty()) {
      ++ans;
      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 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 ans;
          if (!seen.contains(word)) {
            q.offer(word);
            seen.add(word);
          }
          sb.setCharAt(i, cache);
          // Decrease 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 ans;
          if (!seen.contains(word)) {
            q.offer(word);
            seen.add(word);
          }
          sb.setCharAt(i, cache);
        }
      }
    }

    return -1;
  }
}