Skip to content
UoL CS Notes

Graphs - 4 - Traversals

COMP108 Lectures

There are two main traversal algorithms: BFS and DFS. These have been covered in the following COMP111 lectures:

BFS with a Queue/Linked List

Example

Suppose $a$ is the starting vertex:

graph LR
a((a)) --- b((b))
a --- e((e))
a --- d((d))
b --- f((f))
e --- f
d --- h((h))
f --- c((c))
e --- k((k))
e --- g((g))
f --- k

This would generate the following queues when searching with BFS:

  1. $\text{head}\rightarrow a\leftarrow\text{tail}$
  2. $\text{head}\rightarrow b\rightarrow d\rightarrow e\leftarrow\text{tail}$
  3. $\text{head}\rightarrow d\rightarrow e\rightarrow f\leftarrow\text{tail}$
  4. $\text{head}\rightarrow d\rightarrow e\rightarrow f\leftarrow\text{tail}$
  5. $\text{head}\rightarrow f\rightarrow h\rightarrow g\rightarrow k\leftarrow\text{tail}$
  6. $\text{head}\rightarrow h\rightarrow g\rightarrow k\rightarrow c\leftarrow\text{tail}$
  7. $\text{head}\rightarrow g\rightarrow k\rightarrow c\leftarrow\text{tail}$
  8. $\text{head}\rightarrow k\rightarrow c\leftarrow\text{tail}$
  9. $\text{head}\rightarrow c\leftarrow\text{tail}$

Every time an element is removed from the queue, it is added to the traversal:

BFS: $a,b,d,e,f,h,g,k,c$

Pseudo Code

unmark all vertices
choose some starting vertex s
mark s and insert s into tail of list L
while L is non-empty do
begin
	remove a vertex v from head of L
	visit v 	// print its data
	for each unmarked neighbour w of v do
		mark w and insert w into tail of list L
end

DFS with Stack

Example

Suppose $a$ is the starting vertex:

graph LR
a((a)) --- b((b))
a --- e((e))
a --- d((d))
b --- f((f))
e --- f
d --- h((h))
f --- c((c))
e --- k((k))
e --- g((g))
f --- k

This would generate the following stacks when searching with DFS:

  1. $\mathbf a\leftarrow \text{top}$
  2. $e,d,\mathbf b\leftarrow \text{top}$
  3. $e,d,\mathbf f\leftarrow \text{top}$
  4. $e,d,k,e,\mathbf c\leftarrow \text{top}$
  5. $e,d,k,\mathbf e\leftarrow \text{top}$
  6. $e,d,k,k,\mathbf g\leftarrow \text{top}$
  7. $e,d,k,\mathbf k\leftarrow \text{top}$
  8. $e,d,k\leftarrow \text{top}$

    Not added to path as it already exists.

  9. $e,\mathbf d\leftarrow \text{top}$
  10. $e,\mathbf h\leftarrow \text{top}$
  11. $e\leftarrow\text{top}$

    Not added to path as it already exists.

Every time a unique element is popped from the stack, it is added to the traversal:

DFS: $a,b,f,c,e,g,k$

Pseudo Code

unmark all vertices
push starting vertex u onto top of stack S
while S is non-empty do
begin
	pop a vertex v from top of S
	if v is unmarked then
	begin
		visit and mark v
		for each unmarked neighbour w of v do
			push w onto top of S
	end
end