HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Prim's algorithm for finding the minimum spanning tree

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
theminimumalgorithmprimforfindingspanningtree

Problem

So I was coding Prim's algorithm for practice and this is what I wrote. It works for finding the weight of the minimum spanning tree (MST) but I'm wondering if the loop I am doing to add the the edges in the frontier to the minheap is optimal.

import heapq
from collections import defaultdict
g = defaultdict(list)
weight = 0 
connected = set([])
pq = []

#n is the number of nodes m is the number of edges
n, m = [int(x) for x in raw_input().split(" ")]
#create adjacency list from inputs of the form "vertex1 vertex2 weight"
for _ in xrange(m):
    a, b, w = [int(x) for x in raw_input().split(" ")]
    g[a].append((w, b))
    g[b].append((w, a))

start = int(raw_input())
connected.add(start)
for tup in g[start]:
    heapq.heappush(pq, tup)
while pq:
    w, b = heapq.heappop(pq)
    if b not in connected:
        weight += w
        connected.add(b)
        #by how much does this loop affect the run time of Prims?
        for tup in g[b]:
            heapq.heappush(pq, tup)

print weight

Solution

#n is the number of nodes m is the number of edges
n, m = [int(x) for x in raw_input().split(" ")]


well, instead of writing this comment it would be much better to give your variables meaningful and descriptive names, In this way you won't have to read the comment and the variables to know what they are about.

The same applies to g, pq, a.........etc.etc

Code Snippets

#n is the number of nodes m is the number of edges
n, m = [int(x) for x in raw_input().split(" ")]

Context

StackExchange Code Review Q#138271, answer score: 2

Revisions (0)

No revisions yet.