COMP20007 Design of Algorithms: Graph Traversal
COMP20007 Design of Algorithms: Graph Traversal
Graph Traversal
Lars Kulik
Lecture 7
Semester 1, 2022
1
Breadth-First and Depth-First Traversal
3
Depth-First Search: The Traversal Stack
a c
DFS corresponds to using a
f stack discipline for keeping
d track of where we are in the
b e g overall process.
4
Depth-First Search: The Traversal Stack
5
Depth-First Search: The Depth-First Search Forest
back edge → d
6
Depth-First Search: The Algorithm
function DFS(hV , E i)
mark each node in V with 0
count ← 0
for each v in V do
if v is marked 0 then
DfsExplore(v )
function DfsExplore(v )
count ← count + 1
mark v with count
for each edge (v , w ) do ⊲ w is v ’s neighbour
if w is marked with 0 then
DfsExplore(w )
How? ✎
9
Applications of Depth-First Search
How? ✎
It is also easy to adapt it so that it can decide whether a graph has
a cycle.
How? ✎
9
Applications of Depth-First Search
How? ✎
It is also easy to adapt it so that it can decide whether a graph has
a cycle.
How? ✎
In terms of DFS forests, how can we tell if we have traversed a
dag?
9
Breadth-First Search
10
Depth-First Search vs Breadth-First
a a
• • • • • • • • • •
• • • • • •
• • • • • • • •
• • • •
• • • •
• • • • • •
• • • • • • • • • •
11
Breadth-First Search: The Traversal Queue
a1
f
d b2 c3 d4 e5
e g c3 d4 e5
b
d4 e5 f6
e5 f6
f6
g7
a c a
tree edge →
f b c d e
d
b e g ր f
cross edge
g
13
Breadth-First Search: The Algorithm
function BFS(hV , E i)
mark each node in V with 0
count ← 0, init(queue) ⊲ create an empty queue
for each v in V do
if v is marked 0 then
count ← count + 1
mark v with count
inject(queue, v ) ⊲ queue containing just v
while queue is non-empty do
u ← eject(queue) ⊲ dequeues u
for each edge (u, w ) adjacent to u do
if w is marked with 0 then
count ← count + 1
mark w with count
inject(queue, w ) ⊲ enqueues w
14
Breadth-First Search: The Algorithm
For example, given a graph and two nodes, a and b in the graph,
how would you find the fewest number of edges between two given
vertices a and b?
15
Topological Sorting
Then we should try to linearize the graph, that is, order the nodes
in a sequence v1 , v2 , . . . , vn such that for each edge (vi , vj ) ∈ E , we
have i < j.
16
Topological Sorting: Example
a c e
b d f
Here is one:
b a d c e f
17
Topological Sorting Algorithm 1
1. Perform DFS and note the order in which nodes are popped
off the stack.
2. List the nodes in the reverse of that order.
18
Topological Sorting Example Again
a c e
e3,1 f4,2
c2,3 d6,5
a1,4 b5,6
b d f
19
Topological Sorting Algorithm 2
20