



3.1 Depth-First Traversal
Let G = (V, E) is a graph which is represented by an adjacency matrix Adj. Assume that nodes in a graph record visited/unvisited information.
procedure DEPTH-FIRST (G) 1. Initialize all vertices as "unvisited". 2. Let S be a stack. 3. Push the root on S. 4. While S not empty, do 5. begin 6. Let n <- Pop S. 7 If n is marked as "unvisited", then 8. begin 9. Mark n as "visited", and output n to the terminal. 10. For each vertex v in Adj[n], do 11. If v is marked as "unvisited", then // this test is actually redundant 12. push v on S. 13. end 14. end


3.2 Breadth-First Traversal
procedure BREADTH-FIRST (G) 1. Initialize all vertices as "unvisited". 2. Let Q be a queue. 3. Enqueue the root on Q. 4. While Q not empty, do 5. begin 6. n <- Dequeue Q. 7. If n is marked as "unvisited", then 8. begin 9. Mark n as "visited", and output n to the terminal. 10. For each vertex v in Adj[n], do 11. If v is marked "unvisited", then 12. enqueue v on Q.13. end 14. end
6.1 Prim's Algorithm
Let G = (V, E) which is represented by an adjacency list Adj. Some support data structures:
PRIM(G, s)
1. Initialize d[s] with 0, P[s] with 0, and
all other d[i] (i!=s) with a positive infinity and
p[i] (i!=s) with 0.
2. Q <- V // initialize Q with all vertices as UNKNOWN
3. while Q not empty do
4. begin
5. u <- ExtractMin(Q) // Q is modified
6. Mark u as KNOWN // Dequeing u is the same as marking it as KNOWN
7. for each vertex v in Adj[u] do
8. begin
9. if v is UNKNOWN and d[v] > weight(u, v), then do
10. begin
11. d[v] = weight(u, v) // update with shorter weight
12. p[v] = u // update v's parent as v
13. end
14. end
15. end
Example (NOTE: v0 is the source vertex, and d[i] for each vertex i is also indicated in its circle):


6.2 Kruskal's Algorithm
Let G = (V, E) which is represented by an adjacency list Adj. Some support data structures:
KRUSKAL(G)
1. Let F be a set of singleton set of all vertices in G.
2. MST <- {}
3. Q <- E
4. while Q not empty do
5. (u, v) <- ExtractMin(Q) // Q is modified
6. if FIND-SET(u) != FIND-SET(v) then // FIND-SET(i) returns the set in F
// which vertex i belongs to.
// This effectively does cycle check.
// If ACCEPTED,
7. begin
8. merge(FIND-SET(u),FIND-SET(v)) in F
9. MST <- MST Union {(u, v)}
10. end
11. return MST.
NOTE: In the figure below, a number in a vertex indicates the vertex number (NOT any kind of value).
