具有邻接矩阵的未加权图上的最长路径

问题描述

我首先查看了其他问题,但没有找到任何正确的答案。 假设有一个二维数组,其中保存了两个节点,并且还输入了一个整数,其中包含所有节点的总数。 现在的任务是在 Java 的有向无环图中找到最长的路径。

我首先想到了运行 Bfs,例如:

long longestPath(long length,long Array[][])
{
int[] max = new int;
if( !visited(V)
    {dfs(v); maximum[] = max[dfs.distance};}
}

我到此为止,因为我认为 dfs 只对树有效。然后我有了使用拓扑排序的想法。确实我不知道,如何用二维数组实现它。有人有想法吗?

enter image description here

解决方法

是的,你必须做拓扑排序。 DAG 中的最长路径可以通过巧妙的转换找到,即使用当前边权重的负值。在新变换的图中,您找到最短路径。而这个值的负数就是最长的路径。

要找到 DAG 中的最短路径,首先要进行最高排序,然后按该顺序更新

// do this for all the valid adjacent edges according to your matrix
// u is the current vertex you are processing in the topological order
if(cost[u] + w < cost[v]) // assume the edge is from u to v 
{
    cost[v] = cost[u] + w;
}