Approach
Breadth-first search
For Minimum Genetic Mutation, 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
- 32 lines of Java from the credited upstream file 433.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup, work queue.
- 4 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 minMutation(String startGene, String endGene, String[] bank) {3 Set<String> bankSet = new HashSet<>(Arrays.asList(bank));4 if (!bankSet.contains(endGene))5 return -1;6 7 final char[] GENES = new char[] {'A', 'C', 'G', 'T'};8 Queue<String> q = new ArrayDeque<>(List.of(startGene));9 10 for (int step = 1; !q.isEmpty(); ++step)11 for (int sz = q.size(); sz > 0; --sz) {12 StringBuilder sb = new StringBuilder(q.poll());13 for (int j = 0; j < sb.length(); ++j) {14 final char cache = sb.charAt(j);15 for (final char c : GENES) {16 sb.setCharAt(j, c);17 final String word = sb.toString();18 if (word.equals(endGene))19 return step;20 if (bankSet.contains(word)) {21 bankSet.remove(word);22 q.offer(word);23 }24 }25 sb.setCharAt(j, cache);26 }27 }28 29 return -1;30 }31}32