为什么拓扑排序找到最短路径O(V + E)

时间:2015-09-25 19:10:27

标签: algorithm shortest-path topological-sort

我很困惑为什么最短路径的拓扑排序是O(V + E)的Big-O。 这是算法:

1. Topologically sort G into L;
2. Set the distance to the source to 0;
3. Set the distances to all other vertices to infinity;
4. For each vertex u in L
5.    - Walk through all neighbors v of u;
6.    - If dist(v) > dist(u) + w(u, v) 
7.       - Set dist(v) <- dist(u) + w(u, v);

对我而言,它是O(V * E)而不是O(V + E)因为它有2个嵌套for循环。但根据维基百科它的O(V + E),我在这里错过了什么吗? https://en.wikipedia.org/wiki/Topological_sorting#Application_to_shortest_path_finding

1 个答案:

答案 0 :(得分:2)

请记住,边是有向的,因此不会考虑多个顶点的相同边。尽管有嵌套循环,但最终只能查看每个顶点和每个边缘一次。