Graph HW5 Full Solution
Graph HW5 Full Solution
Q1: Adjacency list and matrix for a complete binary tree with 7 vertices (1 to 7):
Binary tree:
/\
2 3
/\/\
4 56 7
Adjacency List:
1: 2, 3
2: 4, 5
3: 6, 7
4:
5:
6:
7:
Adjacency Matrix:
1234567
1[0110000]
2[0001100]
3[0000011]
4[0000000]
5[0000000]
6[0000000]
7[0000000]
3: 0, 4: 1, 5: 1, 1: 2, 2: 2, 6: INF
pi (predecessor):
3: NIL, 4: 3, 5: 3, 1: 4, 2: 5, 6: NIL
Vertices: u, v, w, x, y, z, r, s, t
d:
u: 0, v: 1, w: 1, x: 2, y: 2, z: 2, r: 3, s: 3, t: 3
pi:
u: NIL, v: u, w: u, x: v, y: v, z: w, r: x, s: y, t: z
Order of discovery: S, D, A, E, B, F, G, C
Pseudocode:
DFS(G):
time = 0
if u.color == WHITE:
STACK-DFS(u)
STACK-DFS(u):
create stack S
push u
v = S.pop()
if v.color == WHITE:
v.color = GRAY
if w.color == WHITE:
w.pi = v
push w
v.color = BLACK
If G is undirected:
Only tree and back edges appear (since every edge is bidirectional)
Visit order: q, r, s, t, u, v, w, x, y, z
Label discovery and finish times; classify edges as Tree, Back, Forward, Cross
To handle this, loop through row i of matrix to find adjacent vertices in O(V)
Traverse each edge exactly once in each direction (like undirected DFS)