algorithm - 如何计算两个单词之间的 "shortest distance"?

标签 algorithm data-structures graph-theory

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

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

最佳答案

根据这个拼字游戏列表,猫和狗之间的最短路径是: ['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']

关于algorithm - 如何计算两个单词之间的 "shortest distance"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11811918/

相关文章:

对齐和比较两组可能不完整且忽略缩放的向量的算法?

c# - 找出所有给定数组中公共(public)元素的最佳算法

java - 大内存(数据大小)采集

c# - 支持通过索引和键访问的数据结构

recursion - 用 "E"边计算所有可能连通的平面图

java - 离散余弦变换实现

c# - TryParse 循环中的两个变量

c# - 用于查找数组中少数元素之和的 ParallelFor 代码(子集问题)

algorithm - 给定图 G 中所有可能配置的集合是什么意思

python - 包含图中所有节点和边的字典