Trie中的最短路径

Shortest Path in a Trie

本文关键字:最短路径 Trie      更新时间:2023-10-16

对于数据结构项目,我必须找到像"cat"answers"dog "这样的两个单词之间的最短路径,但我一次只允许更改一个字母。我试图通过实现一个树来实现它,但似乎无法实现最短路径搜索。

cat -> cot -> cog -> dog

所有的单词都是相同的长度,我从字典文件中填充它们。我们必须逐字逐句。因此,中间的单词必须是一个有效的单词。

我认为这是不可能使用一个尝试,但有人知道吗?

您想使用VP-Tree,该算法称为Levenshtein距离可以在这里找到一个C实现,代码太长了,不能作为答案发布:
C VP-Tree

对于这类问题,更好的数据结构是图。它被称为word ladder你可以在这里查看:http://en.wikipedia.org/wiki/Word_ladder。

你要找的是一个简单的BFS。每个单词都是一个图顶点,但甚至不需要构建图,您可以使用单词数组来解决它:

words = {"cat", "dog", "dot", "cot"}
mark = {0, 0, 0, 0}
distance = {0, 0, 0, 0}
queue Q
start_word_index = 0; // words[0] -> "cat"
destination_word_index = 1; // words[1] -> "dog"
Q.push(start_word_index)
while(Q is not empty) {
    word_index = Q.pop()
    for each `words[j]` {
        if (difference between `words[word_index]` and `words[j]` is only 1 character) AND
           (`mark[j]` is not 1) {
            mark[j] = 1
            Q.push(j)
            distance[j] = distance[word_index] + 1
        }
    }
}
if mark[destination_word_index] is 0 {
    print "Not reachable"
} else {
    print "Distance is ", distance[destination_word_index]
}