CS 236 – Discrete Mathematics

Adjacency Lists;
Breadth-First Search &
Depth-First Search
Adjacency Lists
For directed graphs:
a
b
c
a a b c
b c
c b
Simple Notation
{ (a,a), (a,b), (a,c), (b,c), (c,b) }
1
a
1
2
b
3
3
c
2
a b c
a 1 1 1
b 0 0 1
c 0 1 0
2
3
Space: Adjacency Lists vs. Matricies
• Space (n vertices and m edges)
– matrix: n2 + n(vertex-name size)
• = matrix size + header size
• matrix can be bits, but bits are not directly addressable
– list: n(header-node size) + m(list-node size)
• Sparse: few edges  0 in the extreme case
– Matrix  fixed size: so no size benefit
– List  variable size: as little as n(vertex-node size)
• Dense: many edges  n2 in the extreme case
– Matrix  fixed size: so no size loss
– List  variable size: as much as n(header-node
size) + n2(list-node size)
Operations: Adjacency Lists vs. Matricies
• Operations depend on sparse/dense and what’s being done.
• Examples (n nodes and m edges)
– Is there an arc from x to y?
• Matrix: O(1)  check value at (x, y)
• List: O(n)  index to x, traverse list to y or end
– Get successor nodes of a node.
• Matrix: O(n)  scan a row
• List: O(n)  traverse a linked list
– Get predecessor nodes of a node.
• Matrix: O(n)  scan a column
• List: O(n+m)  traverse all linked lists, which could be as bad as
O(n+n2) = O(n2).
Adjacency Lists for Undirected and
Weighted Graphs
• Undirected Graphs:
1
a
3
5
b
7
c
a a b c
b a c
Make each edge (except
loops) go both ways.
c a b
• Weighted Graphs:
a
b
c
(a,1) (b,5) (c,3)
(a,5) (c,7)
(a,3) (b,7)
- add additional field to node
- node-weight pairs
Breadth-First Search (BFS)
Mark start node and enqueue
While queue is not empty
BFS Algorithm
Dequeue N
For each neighbor X of N
Marked
a
If X is not marked
Mark X and enqueue
b
c
a
c
b
d
d
N
a
a
a
b
c
c
d
Queue
a
b
bc
c
d
-
Undirected edges:
each edge twice
Search order: a b c d
= O(n+2m)
= O(m) if m>>n
Depth-First Search (DFS)
DFS (start node)
Proc DFS (N)
DFS Algorithm
Mark N
For each neighbor X of N
If X is not marked
DFS (X)
a
Marked
N
a
a
a
b
b
c
c
d
c
b
a
b
c
c
b
d
d
DFS
a
b
c
d
Search order: a b c d
= O(n+2m)
= O(m) if m>>n
BFS vs. DFS
Marked
a
b
c
e
d
f
N
a
a
a
a
b
b
c
c
e
d
f
a
Queue
a
b
bc
bce
ce
ced
ed
edf
df
f
-
e
b
c
f
BFS Order: a b c e d f
d
BFS vs. DFS
Marked
N
a
a
a
b
b
c
c
f
c
b
d
b
a
e
a
b
c
f
d
e
a
DFS
a
b
e
b
c
d
f
c
f
d
e
DFS Order: a b c f d e
(BFS Order: a b c e d f)
BFS & DFS with Directed Graphs
a
b
c
e
j
a
f
k
d
g
l
h
b
i
m
c
e
n
j
f
k
d
g
h
l
i
m
BFS
DFS
a,b,c,d,e,f,g,h,i,j,k,l,m,n
a,b,e,j,f,k,l,h,c,g,d,i,m,n
Same as before, by chance
Not same as before
n