Dsa Graph Prim Mst
DodaTech
1 min read
In this tutorial, you'll learn about How to Fix Prim's MST Errors. We cover key concepts, practical examples, and best practices.
Fix prim's mst errors when connected tracking wrong or edge weights not properly prioritized.
Quick Fix
Wrong
def prim(g):
s=next(iter(g)); mst=[]; vis=set()
pq=[(0,s,None)]
while pq:
w,u,p=heapq.heappop(pq)
vis.add(u)
if p: mst.append((p,u,w))
for v,w in g[u]: heapq.heappush(pq,(w,v,u))
Adds all edges without checking if node already visited. Heavy memory.
Right
import heapq
def prim(g):
s=next(iter(g)); mst=[]; vis={s}
pq=[(w,s,v) for v,w in g[s]]; heapq.heapify(pq)
while pq and len(vis)<len(g):
w,u,v=heapq.heappop(pq)
if v in vis: continue
vis.add(v); mst.append((u,v,w))
for nb,w in g[v]:
if nb not in vis: heapq.heappush(pq,(w,v,nb))
return mst
Graph {0:[(1,4),(2,1)],1:[(0,4),(2,2),(3,1)],2:[(0,1),(1,2),(3,5)],3:[(1,1),(2,5)]} -> [(0,2,1),(2,1,2),(1,3,1)]. O(E log V).
Prevention
Only push edges from newly visited nodes. Skip if destination already visited.
DodaTech Tools
Doda Browser's algorithm visualizer steps through DSA operations line by line. DodaZIP archives implementation patterns for team sharing. Durga Antivirus Pro detects memory corruption patterns in algorithm implementations.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro