You are on page 1of 1

DFS(G)

for each vertex u in G.V


u.color = white
u.pi = nil
time = 0
for each vertex u in G.V
if u.color == white
dfs-visit(G,u)

// tree edge v first discovered from (u,v)


// back connect u to v ancestor
// forward nontree from u to v
// cross all others, cousins, and diff trees
// when first explore (u,v) if v is color:
// white: tree
// gray: back
// black: forward or cross

DFS-Visit(G, u)
time = time + 1
u.d = time
u.color = gray
for each v in G.adj[u]
if v.color == white
v.pi = u
dfs-visit(G,v)
u.color = black
time = time + 1
u.f = time
Components(G)
call DFS(G) to get u.f for each vertex u
compute G^T (reverse the direction of each edge)
call DFS(G^T), but in main loop, order vertices in decreasing of u.f
output vertices of each tree in depth-first forest formed in line 3 as a separate component
safe edge maintains invariant that A is a subset of a MST
MSTs are acyclic, contain all vertices,
Generic-MST(G, w)
A = null set
while A does not form spanning tree
find edge (u,v) that is safe for A
A = A U {(u,v)}
return A
kruskal and prim are specific implementations of gen-mst: they specify how to do line 3
Kruskal(G,w) O(ElgV)
A = null set
for each vertex v in G.V
make-set(v)
sort edges of G.E into nondecreasing order by weight w
for each edge (u,v) in G.E, in nondecreasing order
if find-set(u) != find-set(v)
A = A U {(u,v)}
union(u,v)
return A
Prim(G, w, r) O(E + VlgV)
for each u in G.V
u.key = INF // Q based on key, which is min weight of single edge connecting v to tree
u.pi = nil
r.key = 0
Q = G.V
while Q != null set
u = extract-min(Q)
for each v in G.adj[u]
if v in Q and w(u,v) < v.key
v.pi = u
v.key = w(u,v)
relax(u, v, w)
if v.d > u.d + w(u,v)
v.d = u.d + w(u,v)
v.pi = u
init-single-source(G,s)
for each v in G.V
v.d = INF
v.pi = nil
s.d = 0

Dijkstra(G, w, s)
init-single-source(G,s)
S = null set
Q = G.V
while Q != null set
u = extract-min(Q)
S = S U {u}
for each v in G.adj[u]
relax(u,v,w)

You might also like