Problem Link:
http://oj.leetcode.com/problems/word-ladder/
Two typical techniques are inspected in this problem:
- Hash Table. One hash set is the words dictionary where we can check if a
word is in the dictionary in O(1) time. The other hash set is used to store
all visited words we already checked. - Double-direction BFS. To accelerate the process that finds the shortest
path between start word and end word, we need carry on a special BFS from both
start word and end word. If there exists a path between start word and end
word, then two fronts must meet at some time.
One simple solution for this problem is BFS from the start word, we keep a
list of edge words (the last word of each path). Each time, we search all
unvisited words next to the edge words, and add these new found
words into the new edge list. The program return the length of the path when the
end words is reached, or return 0 if no unvisited words can be found.
However, I implemented this BFS but got a TLE. So I adapted a
double-direction BFS which may half the running time, and is
accepted by the leetcode judge. The algorithm can go as follows.
Let start_front be the list of edge words of BFS paths from the start word
Let end_front be the list of edge words of BFS paths from the end word
Initialize start_front = [start] and end_front = [end]
Start a double direction BFS loop, in each iteration we extend the two fronts as follows:
For each word w in start_front
Find all transformable words of w those are not visited yet
Let all new found words be the new start_font, return 0 if no new words found
If two fronts meet, then return the number of transforms
For each word w in end_front
Find all transformable words of w those are not visited yet
Let all new found words be the new end_front, return 0 if no new words found
If two fronts meet, then return the number of transforms
The following code is the python implementatation which is accepted by
leetcode.com.
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 |
|
【LeetCode OJ】Word Ladder I,布布扣,bubuko.com