顿搜
飞过闲红千叶,夕岸在哪
类目归类
Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transformation sequence(s) from beginWord to endWord, such that:
Only one letter can be changed at a time
Each transformed word must exist in the word list. Note that beginWord is not a transformed word.
Given:
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log","cog"]
Return
[
["hit","hot","dot","dog","cog"],
["hit","hot","lot","log","cog"]
]
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public class LeetCode0126_BFS {
class Node {
String str;
int level;
Node parent;
public Node(String str, int level, Node parent) {
this.str = str;
this.level = level;
this.parent = parent;
}
}
public List> findLadders(String beginWord, String endWord, List wordList) {
List> result = new ArrayList>();
if (wordList == null || wordList.size() == 0) {
return result;
}
Queue queue = new LinkedList();
queue.add(new Node(beginWord, 1, null));
int min = wordList.size() + 1;
HashSet visited = new HashSet();
HashSet unvisited = new HashSet();
unvisited.addAll(wordList);
int preLevel = 0;
while (!queue.isEmpty()) {
Node node = queue.poll();
if (node.level > min) {
continue;
}
if (endWord.equals(node.str)) {
Node p = node;
min = p.level;
LinkedList res = new LinkedList();
while (p != null) {
res.addFirst(p.str);
p = p.parent;
}
result.add(res);
continue;
}
if (preLevel < node.level) {
preLevel = node.level;
unvisited.removeAll(visited);
}
char[] arr = node.str.toCharArray();
for (int i = 0; i < arr.length; i++) {
char c = arr[i];
for (char j = 'a'; j <= 'z'; j++) {
arr[i] = j;
String newStr = new String(arr);
if (!unvisited.contains(newStr)) {
continue;
}
visited.add(newStr);
Node newNode = new Node(newStr, node.level + 1, node);
queue.offer(newNode);
}
arr[i] = c;
}
}
return result;
}
public static void main(String[] args) {
LeetCode0126_BFS leetcode = new LeetCode0126_BFS();
List wordList = new ArrayList(Arrays.asList("hot", "dot", "dog", "lot", "log", "cog"));
List> result = leetcode.findLadders("hit", "cog", wordList);
for (int i = 0; i < result.size(); i++) {
System.out.println((result.get(i).toString()));
}
}
}