Lecture 15 Bis
Lecture 15 Bis
KRUSKAL ALGORITHM
1
Cycle checking
• How to check if adding (C, F) causes cycle?
2
Cycle checking
• How to check if adding (C, F) causes cycle?
3
Cycle checking
• How to check if adding (C, F) causes cycle?
4
Cycle checking
• How to check if adding (I, G) causes cycle?
5
Cycle checking
• How to check if adding (u, v) causes cycle?
• u and v are in different components => no cycle,
merge two components into one.
6
Implementation
• Data structure (Set) which supports three operators:
• makeSet(u): create a component which contains only u
• find(u): find the component containing u
• union(u, v): merge the component that u is in with the
component that v is in.
7
Implementation
• Simple implementation: tree!
• parent[u]: the parent of node u
parent[A] = A
parent[B] = A
parent[G] = G
parent[C] = G
parent[I] = C
parent[H] = G
parent[F] = G
parent[D] = D
parent[E] = D
8
Implementation
• find(u): returns the root of the three that u is in.
find(u) {
while(u != parent[u])
u = parent[u];
return u;
}
find(I) returns G
9
Implementation
• union(root_u, root_v): merges two trees
union(root_u, root_v) {
return parent[root_v] = root_u;
}
union(A, G)
10
Implementation
Kruskal(G = (V,E)):
• Sort the edges in E by non-decreasing weight.
• MST={}
• for u in V Kruskal(G = (V,E)):
• parent[u] = u • Sort the edges in E by non-
decreasing weight.
• for e in E (in sorted order): • MST={}
• root_u = find(u) • for e in E (in sorted order):
• root_v = find(v) • if adding e to MST won’t
• if root_u != root_v: cause a cycle:
• add e to MST • add e to MST.
• parent[root_v] = root_u • return MST
• return MST
11
Example
12
Sort edges
13
Connected components
14
For edge in edges
15
For edge in edges
16
For edge in edges
17
For edge in edges
18
For edge in edges
19
Example
20
THANK YOU
21