What is the exact difference between Dijkstra's and Prim's algorithms? I know Prim's will give a MST but the tree generated by Dijkstra will also be a MST. Then what is the exact difference?
相关问题
- Finding k smallest elements in a min heap - worst-
- binary search tree path list
- High cost encryption but less cost decryption
- How to get a fixed number of evenly spaced points
- How to determine +/- sign when calculating diagona
相关文章
- Mercurial Commit Charts / Graphs [closed]
- What are the problems associated to Best First Sea
- Coin change DP solution to keep track of coins
- Algorithm for partially filling a polygonal mesh
- Robust polygon normal calculation
- Algorithm for maximizing coverage of rectangular a
- How to measure complexity of a string?
- Select unique/deduplication in SSE/AVX
The key difference between the basic algorithms lies in their different edge-selection criteria. Generally, they both use a priority queue for selecting next nodes, but have different criteria to select the adjacent nodes of current processing nodes: Prim's Algorithm requires the next adjacent nodes must be also kept in the queue, while Dijkstra's Algorithm does not:
The calculations of vertex.distance are the second different point.
@templatetypedef has covered difference between MST and shortest path. I've covered the algorithm difference in another So answer by demonstrating that both can be implemented using same generic algorithm that takes one more parameter as input: function
f(u,v)
. The difference between Prim and Dijkstra's algorithm is simply whichf(u,v)
you use.At the code level, the other difference is the API.
You initialize Prim with a source vertex, s, i.e.,
Prim.new(s)
; s can be any vertex, and regardless of s, the end result, which are the edges of the minimum spanning tree (MST) are the same. To get the MST edges, we call the methodedges()
.You initialize Dijkstra with a source vertex, s, i.e.,
Dijkstra.new(s)
that you want to get shortest path/distance to all other vertices. The end results, which are the shortest path/distance from s to all other vertices; are different depending on the s. To get the shortest paths/distances from s to any vertex, v, we call the methodsdistanceTo(v)
andpathTo(v)
respectively.Dijkstra's algorithm doesn't create a MST, it finds the shortest path.
Consider this graph
The shortest path is 9, while the MST is a different 'path' at 10.