diff --git "a/LeetCode/121-130/127. \345\215\225\350\257\215\346\216\245\351\276\231\357\274\210\345\233\260\351\232\276\357\274\211.md" "b/LeetCode/121-130/127. \345\215\225\350\257\215\346\216\245\351\276\231\357\274\210\345\233\260\351\232\276\357\274\211.md" index 5cb1d710..f1ec13d8 100644 --- "a/LeetCode/121-130/127. \345\215\225\350\257\215\346\216\245\351\276\231\357\274\210\345\233\260\351\232\276\357\274\211.md" +++ "b/LeetCode/121-130/127. \345\215\225\350\257\215\346\216\245\351\276\231\357\274\210\345\233\260\351\232\276\357\274\211.md" @@ -168,27 +168,30 @@ class Solution { // update 代表从 deque 中取出一个单词进行扩展, // cur 为当前方向的距离字典;other 为另外一个方向的距离字典 int update(Deque deque, Map cur, Map other) { - // 获取当前需要扩展的原字符串 - String poll = deque.pollFirst(); - int n = poll.length(); + int m = deque.size(); + while (m-- > 0) { + // 获取当前需要扩展的原字符串 + String poll = deque.pollFirst(); + int n = poll.length(); - // 枚举替换原字符串的哪个字符 i - for (int i = 0; i < n; i++) { - // 枚举将 i 替换成哪个小写字母 - for (int j = 0; j < 26; j++) { - // 替换后的字符串 - String sub = poll.substring(0, i) + String.valueOf((char)('a' + j)) + poll.substring(i + 1); - if (set.contains(sub)) { - // 如果该字符串在「当前方向」被记录过(拓展过),跳过即可 - if (cur.containsKey(sub)) continue; - - // 如果该字符串在「另一方向」出现过,说明找到了联通两个方向的最短路 - if (other.containsKey(sub)) { - return cur.get(poll) + 1 + other.get(sub); - } else { - // 否则加入 deque 队列 - deque.addLast(sub); - cur.put(sub, cur.get(poll) + 1); + // 枚举替换原字符串的哪个字符 i + for (int i = 0; i < n; i++) { + // 枚举将 i 替换成哪个小写字母 + for (int j = 0; j < 26; j++) { + // 替换后的字符串 + String sub = poll.substring(0, i) + String.valueOf((char)('a' + j)) + poll.substring(i + 1); + if (set.contains(sub)) { + // 如果该字符串在「当前方向」被记录过(拓展过),跳过即可 + if (cur.containsKey(sub) && cur.get(sub) <= cur.get(poll) + 1) continue; + + // 如果该字符串在「另一方向」出现过,说明找到了联通两个方向的最短路 + if (other.containsKey(sub)) { + return cur.get(poll) + 1 + other.get(sub); + } else { + // 否则加入 deque 队列 + deque.addLast(sub); + cur.put(sub, cur.get(poll) + 1); + } } } }