Problem
Given two words (start and end), and a dictionary, find the length of shortest transformation sequence from start to end, such that:
Only one letter can be changed at a time
Each intermediate word must exist in the dictionary
Notice
Return 0 if there is no such transformation sequence.
All words have the same length.
All words contain only lowercase alphabetic characters.
Example
Given:
start = "hit"
end = "cog"
dict = ["hot","dot","dog","lot","log"]
As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",
return its length 5.
思路
- 一个string的每个字符可以转换成25种新的可能, 所以就像一个图.
- 我们需要找出最短路径, 所以用bfs
- 每次都变换其中一个字符, 如果新的string试过了或者不存在字典里面, 直接pass
- 层序遍历, 每层开始之前路径加一
public int ladderLength(String start, String end, Set<String> dict) {
dict.add(end);
Queue<String> queue = new LinkedList<>();
queue.offer(start);
Set<String> visited = new HashSet<>();
visited.add(start);
int shortest = 0;
while (!queue.isEmpty()) {
int size = queue.size();
shortest++;
for (int i = 0; i < size; i++) {
String curt = queue.poll();
if (curt.equals(end)) return shortest;
for (char c = 'a'; c <= 'z'; c++) {
for (int index = 0; index < curt.length(); index++) {
char[] chs = curt.toCharArray();
chs[index] = c;
String trans = String.valueOf(chs);
if (visited.contains(trans) || !dict.contains(trans)) {
continue;
}
queue.offer(trans);
visited.add(trans);
}
}
}
}
return shortest;
}