我假设您有一个有效单词列表,并且您实际上不是在寻找单个路径(为什么要为此进行优化),而是在寻找很多路径。使用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。