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 42 43 44 45 46 47 48 49 50 51 52 53 54 55
| class Solution { public int openLock(String[] deadends, String target) { Set<String> deadEndSet = new HashSet<>(Arrays.asList(deadends)); Set<String> visitedWordSet = new HashSet<>();
Set<String> q1 = new HashSet<>(); q1.add("0000"); Set<String> q2 = new HashSet<>(); q2.add(target);
int count = 0;
while (!q1.isEmpty() && !q2.isEmpty()) { Set<String> nextLayerWords = new HashSet<>();
for (String word : q1) { if (deadEndSet.contains(word)) { continue; } if (q2.contains(word)) { return count; } visitedWordSet.add(word); for (int i = 0; i < 4; i++) { String upWord = moveUp(word, i); if (!visitedWordSet.contains(upWord)) { nextLayerWords.add(upWord); } String downWord = moveDown(word, i); if (!visitedWordSet.contains(downWord)) { nextLayerWords.add(downWord); } } }
q1 = q2; q2 = nextLayerWords; count++; }
return -1; }
private String moveUp(String word, int i) { char[] chars = word.toCharArray(); chars[i] = chars[i] == '9' ? '0' : (char) (chars[i] + 1); return new String(chars); }
private String moveDown(String word, int i) { char[] chars = word.toCharArray(); chars[i] = chars[i] == '0' ? '9' : (char) (chars[i] - 1); return new String(chars); } }
|
双向 BFS 实现,节省空间。
References
752. Open the Lock
剑指 Offer II 109. 开密码锁