简体   繁体   English

dijkstra最短路径算法的时间复杂度是否取决于所使用的数据结构?

[英]Does time complexity of dijkstra's algorithm for shortest path depends on data structure used?

One way to store the graph is to implement nodes as structures, like 存储图的一种方法是将节点实现为结构,例如

struct node {
int vertex; node* next; 
};

where vertex stores the vertex number and next contains link to the other node. 顶点存储顶点号,下一个包含到另一个节点的链接。

Another way I can think of is to implement it as vectors, like 我可以想到的另一种方法是将其实现为矢量,例如

vector<vector< pair<int,int> > G;

Now, while applying Dijkstra's algorithm for shortest path, we need to build priority queue and other required data structures and so as in case 2 (vector implementation). 现在,在将Dijkstra的算法应用于最短路径时,我们需要建立优先级队列和其他所需的数据结构,例如情况2(向量实现)。 Will there be any difference in complexity in above two different methods of applying graph? 上面两种不同的应用图方法的复杂度是否会有所不同? Which one is preferable? 哪一个更好?

EDIT: In first case, every node is associated with a linked list of nodes which are directly accessible from the given node. 编辑:在第一种情况下,每个节点都与可从给定节点直接访问的节点的链表关联。 In second case, G.size() is the number of vertices in our graph G[i].size() is the number of vertices directly reachable from vertex with index i G[i][j].first is the index of j-th vertex reachable from vertex i G[i][j].second is the length of the edge heading from vertex i to vertex G[i][j].first 在第二种情况下,G.size()是图形G [i]的顶点数。size()是可直接从索引为i G [i] [j]的顶点到达的顶点数。从顶点i G [i] [j] .j可达的第j个顶点是从顶点i到顶点G [i] [j]的边的长度。

Both are adjacency list representations . 两者都是邻接表表示 If implemented correctly, that would be expected to result in the same time complexity. 如果正确实施,那将导致相同的时间复杂度。 You'd get a different time complexity if you use an adjacency matrix representation . 如果使用邻接矩阵表示法,您将获得不同的时间复杂度。

In more detail - this comes down to the difference between an array ( vector ) and a linked-list . 更详细地讲-这归结为数组( vector )和链表之间的区别 When all you're doing is iterating through the entire collection (ie the neighbours of a vertex), as you do in Dijkstra's algorithm, this takes linear time ( O(n) ) regardless of whether you're using an array or linked-list. 当您要做的是遍历整个集合(即顶点的邻居)时,就像您在Dijkstra算法中所做的那样,无论您使用的是数组还是链接的,这都需要线性时间( O(n) )。名单。

The resulting complexity for running Dijkstra's algorithm, as noted on Wikipedia , would be Wikipedia所述 ,运行Dijkstra算法的结果复杂度为:
O(|E| log |V|) with a binary heap in either case. 在任何一种情况下, O(|E| log |V|)带有二进制堆。

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

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