题目描述
Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from start to end, such that:
- Only one letter can be changed at a time
- Each intermediate word must exist in the dictionary
For example,
Given:
start ="hit"
end ="cog"
dict =["hot","dot","dog","lot","log"]
Return
[ ["hit","hot","dot","dog","cog"], ["hit","hot","lot","log","cog"] ]
Note:
- All words have the same length.
- All words contain only lowercase alphabetic characters.
这道题我并没有通过所有测试,在这里想分享一下我的思路
解题思路:
- 建立一个队列,队列初始为start
- 获取当前队列的size,循环poll 直到size = 0; 循环中判断是否当前结果的最后一个字符串与end差1距离
- 如果是,则放入结果队列中,如果不是 从字典中查找每个只差1距离的字符的字符串,然后放入队列中。
import java.util.*;
public class Solution {
public ArrayList<ArrayList<String>> findLadders(String start, String end,
HashSet<String> dict) {
ArrayList<ArrayList<String>> reverse = new ArrayList<>();
ArrayList<ArrayList<String>> res = new ArrayList<>();
if (dict.contains(start)) {
dict.remove(start);
}
LinkedList<ArrayList<String>> queue = new LinkedList<>();
ArrayList<String> init = new ArrayList<>();
init.add(start);
queue.offer(init);
boolean find = false;
HashSet<String> removes = new HashSet<>();
while (!queue.isEmpty() && !find) {
int size = queue.size();
removes.clear();
while (size > 0) {
ArrayList<String> cur = queue.poll();
size--;
String last = cur.get(cur.size() - 1);
if (distance(last, end) == 1) {
ArrayList<String> next = (ArrayList<String>) cur.clone();
next.add(end);
reverse.add(next);
find = true;
} else {
for (Iterator<String> it = dict.iterator(); it.hasNext();) {
String p = it.next();
if (distance(p, last) == 1) {
ArrayList<String> next = (ArrayList<String>) cur.clone();
next.add(p);
queue.offer(next);
removes.add(p);
}
}
}
}
for (Iterator<String>it = removes.iterator(); it.hasNext();) {
dict.remove(it.next());
}
}
for (int i = reverse.size() - 1; i >= 0; i--) {
res.add(reverse.get(i));
}
return res;
}
public int distance(String p, String q) {
int count = 0;
for (int i = 0; i < p.length(); i++) {
if (p.charAt(i) != q.charAt(i)) {
count++;
}
}
return count;
}
}