Difference between Prim's and Dijkstra's algorithms?

前端 未结 15 1884
既然无缘
既然无缘 2020-12-07 06:53

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

15条回答
  •  孤街浪徒
    2020-12-07 07:24

    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:

    def dijkstra(g, s):
        q <- make_priority_queue(VERTEX.distance)
        for each vertex v in g.vertex:
            v.distance <- infinite
            v.predecessor ~> nil
            q.add(v)
        s.distance <- 0
        while not q.is_empty:
            u <- q.extract_min()
            for each adjacent vertex v of u:
                ...
    
    def prim(g, s):
        q <- make_priority_queue(VERTEX.distance)
        for each vertex v in g.vertex:
            v.distance <- infinite
            v.predecessor ~> nil
            q.add(v)
        s.distance <- 0
        while not q.is_empty:
            u <- q.extract_min()
            for each adjacent vertex v of u:
                if v in q and weight(u, v) < v.distance:// <-------selection--------
                ...
    

    The calculations of vertex.distance are the second different point.

提交回复
热议问题