adjacency lists; breadth-first search & depth-first search
TRANSCRIPT
Adjacency Lists;Breadth-First Search &
Depth-First Search
Adjacency Lists
For directed graphs:
b
a
c
1 a 1 2 3
2 b 3
3 c 2bc
cb
cbaa
Simple Notation
{ (a,a), (a,b), (a,c), (b,c), (c,b) }010c
100b
111acba
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:
a a b c
b a c
c a b
Make each edge (except loops) go both ways.
b
a
c5
3
7
1
• Weighted Graphs:
a (a,1) (b,5) (c,3)
b (a,5) (c,7)
c (a,3) (b,7)
- add additional field to node- node-weight pairs
Breadth-First Search (BFS)
BFS Algorithm
Search order:
b
c
d
a
a b c d
= O(n+2m)= O(m) if m>>n
Undirected edges: each edge twice
Mark start node and enqueue
While queue is not empty
Dequeue N
For each neighbor X of N
If X is not marked
Mark X and enqueue
Marked N Queuea - a
a -b a bc a b c
b cc -
d c dd -
Depth-First Search (DFS)
DFS Algorithm
= O(n+2m)= O(m) if m>>n
b
c
d
a
a b c d
DFS (start node)
Proc DFS (N)
Mark N
For each neighbor X of N
If X is not marked
DFS (X)
Marked N DFSa
a aa b
b bb c
c cc d
d dcba
Search order:
BFS vs. DFS a b
e c
f
dMarked N Queuea - a
a -b a bc a b ce a b c e
b c ed b c e d
c e df c e d f
e d fd ff -
BFS Order: a b c e d f
BFS vs. DFS
(BFS Order: a b c e d f)
a b
e c
f
dMarked N DFSa
a aa b
b bb c
c cc f
f fcb d
d dba e
e ea
DFS Order: a b c f d e
a
b c d
e f g h i
j k l m n
BFS & DFS with Directed Graphs
BFS DFS
a
b c d
e f g h i
j k l m n
a,b,c,d,e,f,g,h,i,j,k,l,m,n
Same as before, by chance
a,b,e,j,f,k,l,h,c,g,d,i,m,n
Not same as before