Trie中的最短路径
Shortest Path in a Trie
对于数据结构项目,我必须找到像"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]
}
相关文章:
- 内存效率表示最短路径的方法?
- 用于查找网格中最短路径的算法
- 查找最短路径算法
- BFS 打印最短路径
- 使用 Dijkstra 算法跟踪两个节点之间的最短路径
- 使用C++具有两个数字的最短路径算法.(C++)
- 使用迭代深度优先搜索算法的未加权图的最短路径
- 如何仅在 2 个节点之间获取最短路径,给定邻接列表有向图?
- 如何使用贝尔曼-福特算法返回所有具有捆绑重量的最短路径?
- 使用优先级队列查找所有与 Dijkstra 相同的最短路径
- 尝试在图形中查找最短路径时的无限循环
- C++计算有向图中的最短路径
- 使用BFS存储和打印最短路径
- 如何制作由原始图形的最短路径边组成的新图形
- 有没有一种方法可以使用弗洛伊德-沃歇尔算法给出最短路径,其中存在负权重循环而不允许重叠边缘?
- 加权图的开始和结束的最短路径
- 使 c++11 Dijkstra 实现返回最短路径
- 弗洛伊德最短路径算法C++
- Dijkstra 最短路径算法性能 std::p riority_queue VS std::set.
- Trie中的最短路径