LeetCode127. 單詞接龍
阿新 • • 發佈:2020-12-20
☆☆☆方法1:BFS
☆☆☆☆方法2:雙向BFS,減少搜尋空間大小
程式碼1:BFS
class Solution { public int ladderLength(String beginWord, String endWord, List<String> wordList) { if (!wordList.contains(endWord)) { return 0; } Queue<String> queue = new LinkedList<>();boolean[] visited = new boolean[wordList.size()]; queue.offer(beginWord); int idx = wordList.indexOf(beginWord); if (idx != -1) { visited[idx] = true; } int level = 1; // 初始單詞也算一次 while (!queue.isEmpty()) { int size = queue.size(); level++; for (int i = 0; i < size; i++) { String cur = queue.poll(); for (int j = 0; j < wordList.size(); j++) { if (visited[j]) continue; String s = wordList.get(j); if (canConvert(cur,s)) {if (s.equals(endWord)) { return level; } queue.offer(s); visited[j] = true; } } } } return 0; } private boolean canConvert(String cur, String s) { int diff = 0; for (int i = 0; i < cur.length(); i++) { if (cur.charAt(i) != s.charAt(i)) { diff ++; if (diff > 1) break; } } return diff == 1; } }
程式碼2:雙向BFS
M