Word ladder is a word game invented by Lewis Carroll. A word ladder puzzle begins with two words, and to solve the puzzle one must find a chain of other words to link the two, in which two adjacent words (that is, words in successive steps) differ by one letter. Eg. SPORT <-> SHORTSource: Wikipedia
If you've followed my previous Dijkstra's Shortest Path Algorithm Tutorial, you'll be able to solve this challenge with minimum effort.
Essentially, we create a graph where each word is a vertex and there exists an edge if two words differ by a single character. To find the word ladder is basically running any shortest path algorithm. You could also use a Breadth First Search.
Some important observations
- The length of the source and destination words must be the same for a path to exist.
- The path from source to destination can only contain words of the same length. So we can prune off the rest of the dictionary.
- The graph is undirected.
Here's my implementation, it uses the modules from the tutorial.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys,graphs,itertools | |
def prepare_graph(): | |
diff_by_1 = lambda (x,y): len(x) == len(y) and sum(1 for a,b in zip(x,y) if a != b) == 1 | |
graph = {} | |
for x,y in filter(diff_by_1,itertools.product(words,repeat=2)): | |
if x not in graph: graph[x] = [] | |
if y not in graph: graph[y] = [] | |
graph[x].append( ( y , 1) ) | |
graph[y].append( ( x , 1) ) | |
return graph | |
if __name__ == '__main__': | |
if len(sys.argv) >= 3 and len(sys.argv[1]) == len(sys.argv[2]): | |
src,dst = sys.argv[1:] | |
words = filter(lambda w : len(w) == len(src), sys.stdin.read().split()) #only consider those words with same length as parameter | |
if src in words and dst in words: | |
print graphs.dijkstra(prepare_graph(),src,dst) | |
else: | |
print "Both words should be present in the dictionary." | |
else: | |
print "Missing command line parameters." |
For eg.
C:\>wordladder.py BOX TEN < words.txt (4, ['BOX', 'BOD', 'BED', 'BEN', 'TEN'])
Comments
Post a Comment