首页 > 解决方案 > 有序图伪代码中的最长路径

问题描述

我尝试创建一种算法来找到有序图中的最长路径。有序图的属性是:

我的第一次尝试如下:

set w = v1 and L = 0
While there is edge that leaves from w
    Choose the edge (w, vj) with j as small as possible
    set w = vj and L = L + 1
return L

我不明白为什么这个算法在某些情况下是错误的。你可以给我一个例子吗?

标签: algorithmgraphpseudocodegreedy

解决方案


我的直觉告诉我,只选择最小的j并不意味着在其他地方j将继续是最小的。

假设您有一个图1-> 31 -> 5,但是3 -> 95 -> 7 -> 9其中 9 是最后一个节点。你的算法会1 -> 3 -> 91 -> 5 -> 7 -> 9.

事实上,我不认为你真的可以“挑选”一个分支并继续跟随它到最后并且在任何情况下都是正确的:你必须检查其他分支。

递归方法

这是一种使用简单递归算法的方法,在每个分支处计算路径的长度,然后在有多个分支的节点处返回最长的。

简单的伪代码示例(Python 风格)

class node:
    def longest_path(self):
        if len(self.children) == 0: # No children in this node
            return 1
        child_lengths = []
        for child in self.children:
            child_lengths.append(child.longest_path())
        return max(child_lengths) + 1

推荐阅读