Chapter 44: Prim’s Algorithm

前言

  • Prim’s algorithm, a greedy algorithm used to construct a minimum spanning tree

    • 什麼是spanning tree

      • A spanning tree is a subgraph of an undirected graph, containing all of the graph’s vertices, connected with the fewest number of edge

      • cannot contain a cycle and cannot be disconnected

大綱

  • Example

  • Implementation

    • Helper methods

      • Copying a graph

      • Finding edges

    • Producing a minimum spanning tree

  • Testing your code

  • Performance

Example

Copying a graph

  • Create a minimum spanning tree, you must include all vertices from the original graph.

Finding edges

  • Find and store the edges of every vertex you explore.

Producing a minimum spanning tree

Performance

  • Adding vertices and edges to an adjacency list is O(1)

  • Checking if the set contains a vertex also have a time complexity of O(1)

  • The priority queue is built on top of a heap and insertion takes O(log E).

  • The worst-case time complexity of Prim’s algorithm is O(E log E).

    • This is because, each time you dequeue the smallest edge from the priority queue, you have to traverse all the edges of the destination vertex ( O(E) ) and insert the edge into the priority queue ( O(logE) )

Last updated