Approach
Breadth-first search
For Open the Lock, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 42 lines of Java from the credited upstream file 752.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup, work queue.
- 3 loop blocks detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public int openLock(String[] deadends, String target) {3 Set<String> seen = new HashSet<>(Arrays.asList(deadends));4 if (seen.contains("0000"))5 return -1;6 if (target.equals("0000"))7 return 0;8 9 Queue<String> q = new ArrayDeque<>(List.of("0000"));10 11 for (int step = 1; !q.isEmpty(); ++step)12 for (int sz = q.size(); sz > 0; --sz) {13 StringBuilder sb = new StringBuilder(q.poll());14 for (int i = 0; i < 4; ++i) {15 final char cache = sb.charAt(i);16 17 sb.setCharAt(i, sb.charAt(i) == '9' ? '0' : (char) (sb.charAt(i) + 1));18 String word = sb.toString();19 if (word.equals(target))20 return step;21 if (!seen.contains(word)) {22 q.offer(word);23 seen.add(word);24 }25 sb.setCharAt(i, cache);26 27 sb.setCharAt(i, sb.charAt(i) == '0' ? '9' : (char) (sb.charAt(i) - 1));28 word = sb.toString();29 if (word.equals(target))30 return step;31 if (!seen.contains(word)) {32 q.offer(word);33 seen.add(word);34 }35 sb.setCharAt(i, cache);36 }37 }38 39 return -1;40 }41}42