我假設你有有效的單詞列表,你實際上是不是在找一個單一的路徑(爲什麼你會在乎優化能),但很多路徑。這可以用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's,經典的全部最短路徑算法爲Floyd-Warshall。
兩個單詞之間的路徑是什麼? – 2011-02-25 15:13:48
說明:路徑是一系列單詞,其中每個單詞是通過交換前一個單個字母生成的。 – 2011-02-25 15:32:04