Dsa Graph Kruskal
DodaTech
1 min read
In this tutorial, you'll learn about How to Fix Kruskal's MST Errors. We cover key concepts, practical examples, and best practices.
Fix kruskal's mst errors when cycle detection missing or edges not sorted by weight.
Quick Fix
Wrong
def kruskal(g):
edges=[]
for u in g:
for v,w in g[u]: edges.append((w,u,v))
edges.sort()
mst=[]
for w,u,v in edges:
mst.append((u,v,w)) # no cycle check!
No cycle detection. May introduce cycles in MST.
Right
class DSU:
def find(self,x):
if self.p[x]!=x: self.p[x]=self.find(self.p[x])
return self.p[x]
def union(self,x,y):
self.p[self.find(x)]=self.find(y)
def kruskal(g):
edges=[]
for u in g:
for v,w in g[u]: edges.append((w,u,v))
edges.sort()
dsu=DSU(len(g)); mst=[]
for w,u,v in edges:
if dsu.find(u)!=dsu.find(v):
dsu.union(u,v); mst.append((u,v,w))
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),(1,3,1),(1,2,2)]. O(E log E).
Prevention
Sort edges by weight. Use Union-Find to detect cycles. Only add edge if it connects different components.
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