3

最近我有一个采访,我被要求写一个算法来找到从一个特定单词到给定单词的最小 1 个字母变化,即 Cat->Cot->Cog->Dog

我不希望问题的解决方案只是指导我如何在此算法中使用 BFS?

4

4 回答 4

5

根据这个拼字游戏列表,猫和狗之间的最短路径是:['CAT', 'COT', 'COG', 'DOG']

from urllib import urlopen

def get_words():
    try:
        html = open('three_letter_words.txt').read()
    except IOError:
        html = urlopen('http://www.yak.net/kablooey/scrabble/3letterwords.html').read()
        with open('three_letter_words.txt', 'w') as f:
            f.write(html)

    b = html.find('<PRE>') #ignore the html before the <pre>
    while True:
        a = html.find("<B>", b) + 3
        b = html.find("</B>", a)
        word = html[a: b]
        if word == "ZZZ":
            break
        assert(len(word) == 3)
        yield word

words = list(get_words())

def get_template(word):
    c1, c2, c3 = word[0], word[1], word[2]
    t1 = 1, c1, c2
    t2 = 2, c1, c3
    t3 = 3, c2, c3
    return t1, t2, t3

d = {}
for word in words:
    template = get_template(word)
    for ti in template:
        d[ti] = d.get(ti, []) + [word] #add the word to the set of words with that template

for ti in get_template('COG'):
    print d[ti]
#['COB', 'COD', 'COG', 'COL', 'CON', 'COO', 'COO', 'COP', 'COR', 'COS', 'COT', 'COW', 'COX', 'COY', 'COZ']
#['CIG', 'COG']
# ['BOG', 'COG', 'DOG', 'FOG', 'HOG', 'JOG', 'LOG', 'MOG', 'NOG', 'TOG', 'WOG']

import networkx
G = networkx.Graph()

for word_list in d.values():
    for word1 in word_list:
        for word2 in word_list:
            if word1 != word2:
                G.add_edge(word1, word2)

print G['COG']
#{'COP': {}, 'COS': {}, 'COR': {}, 'CIG': {}, 'COT': {}, 'COW': {}, 'COY': {}, 'COX': {}, 'COZ': {}, 'DOG': {}, 'CON': {}, 'COB': {}, 'COD': {}, 'COL': {}, 'COO': {}, 'LOG': {}, 'TOG': {}, 'JOG': {}, 'BOG': {}, 'HOG': {}, 'FOG': {}, 'WOG': {}, 'NOG': {}, 'MOG': {}}

print networkx.shortest_path(G, 'CAT', 'DOG')
['CAT', 'OCA', 'DOC', 'DOG']

作为奖励,我们可以走得最远:

print max(networkx.all_pairs_shortest_path(G, 'CAT')['CAT'].values(), key=len)
#['CAT', 'CAP', 'YAP', 'YUP', 'YUK']
于 2012-08-05T01:56:01.813 回答
4

乍一看,我想到了Levenshtein 距离,但你需要使用 BFS。所以我认为你应该从构建树开始。给定的单词应该是根,然后下一个节点是首字母改变的单词。下一个节点已更改第二个字母。当您构建图形时,您使用 BFS,当您发现新单词时存储路径长度。在算法结束时选择最小距离。

于 2012-08-04T20:59:53.847 回答
0
  1. 从路径集中的起始词开始。

  2. 如果您的路径集中任何路径的结束词是所需的词,请停止,该路径就是所需的路径。

  3. 将路径集中的每条路径替换为以该路径开头但长一个字的所有可能路径。

  4. 转到第 2 步。

于 2012-08-04T21:07:38.030 回答
0

如果我们开始以广度方式构建从目标词到源词的有向无环图,并且我们进行字典查找以验证在添加词时是否在树中较早看到过该词,那么源词的第一次出现,应该给出从“目标词”到“源词”的反向最短路径。

由此我们可以打印从“源”到“目标”的路径

于 2012-08-05T05:07:09.090 回答