Adjacency List Representation: Episode 38
Adjacency List Representation: Episode 38
Reading: First read two pages about graphs in the Math Primer lecture.
GT 6.1.0, 6.1, 6.2 (skip 6.2.3), 6.3, p.289316 [ca. 25pp, approx. 2h]
This note tries to be complete: it contains both material already explained in
FAAP and some new stuff. After a brief remembering of some elements from
FAAP lecture, we will focus on complexity issues in graph algorithms.
Ingredients: Graphs as mathematical objects, Adjacency List representation,
DFS, BFS
2
1
3
5
For dense graphs, with |E| being close to 12 |V |2 , the adjacency matrix is a more
suitable representation. Adjacency matrix is a two dimensional array, say adj ,
such that adj [v][w] = 1 if there is an edge v w (and adj [v][w] = 0 otherwise). Dense graphs sometimes appear in scientific applications.
0
Depth-First-Search
Searching is among the most common operations on graphs. It is sometimes
also called traversing graphs or visiting (e.g. like in visitor pattern).
D FS -V ISIT(v :vertex)
1
2
3
4
Breadth-First-Search (BFS)
Observe that DFS can be implemented using an explicit stack:
D FS -V ISIT(v : vertex)
1
2
3
4
5
6
7
8
P USH(v)
while stack not empty
do
v P OP
if v has been previously visited
then continue
Record that v has been visited
for each neighbor u of v do P USH(u)
4
0
1
3
1
3
3
4
(a) stack: 0
0
(b) stack: 0 6
6
0
2
1
3
1
3
(d) stack: 0 6 4 3
3
4
(e) stack: 0 6 4 3 5
6
0
2
1
3
1
3
3
4
stack: 0 6 4
stack: 0 6 4 5
(g) stack: 0 6 4
(i) stack: 0
1
3
1
3
(j) stack: 0 2
0
(h) stack: 0 6
(f) stack: 0 6 4 3
6
(c) stack: 0 6 4
6
3
4
(k) stack: 0
(l) stack: 0 1
6
2
1
3
stack: 0
(m) stack: empty
B FS -V ISIT(v : vertex)
1
2
3
4
5
6
7
8
E NQUEUE(v)
while queue not empty
do
v D EQUEUE
if v has been previously visited
then continue
Record that v has been visited
for each neighbor u of v do E NQUEUE(u)
Example in Fig. 4. During the BFS traversal a spanning tree is constructed for
the graph. For exampl in Fig. 4(h) the spanning tree is highlighted in yellow.
This is because during BFS vertices leave the FIFO queue in order of their
distance from the start vertex.
Conclusion: BFS can be used to find a shortest path between two vertices
(shortest = with the minimum number of edges).
Theorem 2. BFS visits all the vertices and edges in a graph in time proportional to
|V | + |E| with the adjacency list, and in time proportional to |V |2 with the adjacency
matrix.
1
3
1
3
(a) queue 0
0
3
4
(b) queue 50 10 20 60
6
(c) queue 10 20 60 05 35 45
6
1
3
1
3
3
4
(d) queue 20 60 05 35 45 01
(e) queue 60 05 35 45 01 02
queue 05 35 45 01 02 06 46
(f) queue 35 45 01 02 06 46
1
3
3
4
(g) queue 45 01 02 06 46 53 43
(h) 01 02 06 46 53 43 54 34 64