有効な単語のリストがあり、実際には単一のパスを探しているのではなく (なぜそれを最適化する必要があるのか)、多くのパスを探していると仮定します。これはnetworkXで非常に簡単に行うことができます:
from networkx import Graph
from networkx.algorithms.shortest_paths import shortest_path, all_pairs_shortest_path
from itertools import combinations
WORDS = {'cat', 'hat', 'sat', 'car', 'cad', 'had', 'pad', 'pat', 'can', 'man'}
def makeGraph(words):
""" create a graph where nodes are words and two words are
connected iff they have one different letter """
G = Graph()
# all word combinations
for a,b in combinations(WORDS,2):
# number of different letters
diff = sum(1 for x,y in zip(a,b) if x!=y)
if diff == 1:
G.add_edge(a,b)
return G
g = makeGraph(WORDS)
# path between two words
print shortest_path(g, 'cat', 'pad')
# generating all shortest paths is way more efficient if you want many paths
paths = all_pairs_shortest_path(g)
print paths['cat']['pad']
例の言葉をくれた@Ducanに感謝します。
これらのアルゴリズムを自分で実装したい場合は、wikipediaで多くの説明を見つけることができます。古典的な単一ソースの最短パス アルゴリズムはDijkstra のものであり、古典的なすべてのペアの最短パス アルゴリズムはFloyd-Warshallです。