Professional Documents
Culture Documents
1
2
3 4
Known = { start }
Discovered = { start }
while ( Discovered ≠ ∅ ) {
take node X out of Discovered
for each successor Y of X
if (Y is not in Known)
Parent[Y] = X
Add Y to Discovered
Add Y to Known
}
Breadth-first Depth-first
5 6
1
Depth-First Spanning Tree Example Breadth-First Spanning Tree Example
7 8
9 10
11 12
2
Algorithms for Finding MST Shortest Path – Dijkstra’s Algorithm
1. Borůvka’s algorithm S=∅
P[ ] = none for all nodes
Add vertices to MST in parallel
C[start] = 0, C[ ] = ∞ for all other nodes
2. Prim’s algorithm while ( not all nodes in S )
Add vertices to MST find node K not in S with smallest C[K]
One at a time add K to S
Closest vertex first for each node J not in S adjacent to K
if ( C[K] + cost of (K,J) < C[J] )
3. Kruskal’s algorithm
C[J] = C[K] + cost of (K,J)
Add edges to MST
P[J] = K
One at a time
Lightest edge first Optimal solution computed with greedy algorithm
13 14
17 18
3
MST – Kruskal’s Algorithm MST – Kruskal’s Algorithm
Traversal approach Connected subgraph approach
Traverse tree starting at X Maintain set of nodes for each connected subgraph
If we can reach Y, adding (X,Y) would create cycle Initialize one connected subgraph for each node
If X, Y in same set, adding (X,Y) would create cycle
Example Otherwise
Question 1. Add edge (X,Y) to spanning tree
x
Add (X,Y) to MST? 2. Merge sets containing X, Y
Answer z ?
No, since can already To test set membership
reach Y from X by Use Union-Find algorithm
w y
traversing MST
19 20
21 22
d
23 24
4
Union-Find Algorithm Ackermann’s Function
Path compression Function A( ) grows fast
Speeds up future Find( ) operations
1. Follow parent pointer(s) to root of tree int A(x,y) { A(2,2) = 7
if (x == 0) A(3,3) = 61
2. Update all nodes along path to point to root
return y+1;
A(4,2) = 265536 – 3
Example if (y == 0) 65536
return A(x – 1, 1); A(4,3) = 22 –3
Find(d) 2 65536
return A(x – 1, A(x, y – 1)); A(4,4) = 22 –3
a a }
So how fast is
b c b c d Union-Find?
25 26
27 28
29