Prims Algorithm

From Rice Wiki
Revision as of 17:56, 20 March 2024 by Rice (talk | contribs) (→‎Analysis)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Approach: Greedy

The approach is to try to add the smallest edges as long as they do not create a cycle; add an edge to the tree that is minimum across the cut of vs. . Unlike Dijkstra's algorithm, the weight of the crossing edge is directly considered (as opposed to the distance from the source node).

Given the MST of , the MST of should be that of plus the edge that connects to that is the shortest.

Implementation

for each u in V:
    key[u] = infinity   // cost array
    pi[u] = infinity    // from array
Q = new PriorityQueue(V)
key[root] = 0
while Q is not empty:
    u = extractMin(Q)
    # Reduce nodes
    for v in adj[u]:
        if v in Q and w[u,v] < key[v]:
            key[v] = w[u,v]

Analysis

Initialization takes O(V). Walk through is O(V + E).

During the walk through, the minimum edge is extracted V times, and the edge priority queue is updated E times. Depending on the data structure used, the runtime is different.

  • For an array, the extraction takes O(V) and the update takes O(1). The overall runtime is O(V^2)
  • For a heap, the extraction takes O(logV) and the update takes O(logV). The overall runtime is O(E logV).

As such, priority queue is slower than array when the graph is dense (where E approaches V^2).

Proof: Greedy

Greeedy strategy: Let the greedy choice be the edge that is smallest that crosses the cut between and .

Name greedy choice: let be the smallest edge that crosses the cut from and .

Given an optimal solution with (r,y), prove that is still optimal.

is still a tree since there is no cycles created.

due to its properties as the greedy choice.

Therefore, must be optimal.