简体   繁体   English

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

[英]longest path on unweighted graph with Adjecency matrix

I first looked at other questions and did not find any proper answer.我首先查看了其他问题,并没有找到任何正确的答案。 Suppose there is a 2 dimensional Array given where two nodes are saved and also as Input an Integer which has the total amount of all nodes.假设有一个二维数组,其中保存了两个节点,并且输入一个 Integer,它具有所有节点的总数。 The task is now to find the longest path in a directed acyclic graph in Java.现在的任务是在 Java 中找到有向无环图中的最长路径。

I firstly had the Idea to run Bfs like:我首先有运行 Bfs 的想法,例如:

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

I stopped here then, because I think dfs does only work for trees.那时我停在这里,因为我认为 dfs 只适用于树。 Then I had the idea to use topological sort.Indeed I dont know, how to implement that with the 2-dimensional array.然后我有了使用拓扑排序的想法。我确实不知道如何用二维数组来实现它。 does anyone have an idea?有人有想法吗?

在此处输入图像描述

Yes, you have to do topological sort.是的,您必须进行拓扑排序。 Longest path in a DAG can be found by doing a clever transformation ie use the negative of the current edge weights. DAG中的最长路径可以通过巧妙的转换来找到,即使用当前边权重的负值。 In the newly transformed graph, you find the shortest path.在新转换的图中,您可以找到最短路径。 And the negative of this value is the longest path.而这个值的负数是最长的路径。

For finding the shortest path in a DAG, you first do a top sort and then update in that order为了在 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM