Skip to content

Commit 38b7186

Browse files
committed
add: shortestTransformationSequence
1 parent d56c50d commit 38b7186

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
import java.util.ArrayDeque;
2+
import java.util.Deque;
3+
import java.util.HashSet;
4+
import java.util.List;
5+
import java.util.Set;
6+
7+
public class ShortestTransformationSequence {
8+
public int shortestTransformationSequence(String start, String end, List<String> dictionary) {
9+
Set<String> dictionarySet = new HashSet<>(dictionary);
10+
if (!dictionarySet.contains(start) && !dictionarySet.contains(end)) {
11+
return 0;
12+
}
13+
if (start == end) {
14+
return 1;
15+
}
16+
String lowerCaseAlphabet = "abcdefghijklmnopqrstuvwxyz";
17+
Deque<String> queue = new ArrayDeque<>();
18+
Set<String> visited = new HashSet<>();
19+
queue.offer(start);
20+
visited.add(start);
21+
int dist = 0;
22+
// Use level-order traversal to find the shortest path from the
23+
// start word to the end word.
24+
while (!queue.isEmpty()) {
25+
int size = queue.size();
26+
for (int j = 0; j < size; j++) {
27+
String currWord = queue.poll();
28+
// If we found the end word, we've reached it via the
29+
// shortest path.
30+
if (currWord.equals(end)) {
31+
return dist + 1;
32+
}
33+
// Generate all possible words that have a one-letter
34+
// difference to the current word.
35+
char[] currWordArray = currWord.toCharArray();
36+
for (int i = 0; i < currWord.length(); i++) {
37+
char tmp = currWordArray[i];
38+
for (char c : lowerCaseAlphabet.toCharArray()) {
39+
currWordArray[i] = c;
40+
String nextWord = new String(currWordArray);
41+
// If 'next_word' exists in the dictionary, it's a
42+
// neighbor of the current word. If unvisited, add it
43+
// to the queue to be processed in the next level.
44+
if (dictionarySet.contains(nextWord) && !visited.contains(nextWord)) {
45+
visited.add(nextWord);
46+
queue.offer(nextWord);
47+
}
48+
}
49+
currWordArray[i] = tmp;
50+
}
51+
}
52+
dist++;
53+
}
54+
// If there is no way to reach the end node, then no path exists.
55+
return 0;
56+
}
57+
}

0 commit comments

Comments
 (0)