03a Graphs
03a Graphs
Undirected Graphs
V = { 1, 2, 3, 4, 5, 6, 7, 8 }
E = { 1-2, 1-3, 2-3, 2-4, 2-5, 3-5, 3-7, 3-8, 4-5, 5-6 }
n=8
m = 11
2
Some Graph Applications
3
Graph Representation: Adjacency Matrix
1 2 3 4 5 6 7 8
1 0 1 1 0 0 0 0 0
2 1 0 1 1 1 0 0 0
3 1 1 0 0 1 0 1 1
4 0 1 0 0 1 0 0 0
5 0 1 1 1 0 1 0 0
6 0 0 0 0 1 0 0 0
7 0 0 1 0 0 0 0 1
8 0 0 1 0 0 0 1 0
4
Graph Representation: Adjacency List
1 2 3
2 1 3 4 5
3 1 2 5 7 8
4 2 5
5 2 3 4 6
6 5
7 3 8
8 3 7
5
Paths and Connectivity
6
Cycles
Def. A cycle is a path v1, v2, …, vk-1, vk in which v1 = vk, k > 2, and the
first k-1 nodes are all distinct.
cycle C = 1-2-4-5-3-1
7
Trees
8
Every connected set has at least n-1 edges
9
Rooted Trees
Rooted tree. Given a tree T, choose a root node r and orient each edge
away from r.
root r
parent of v
child of v
10
3.2 Graph Traversal
Connectivity
s-t shortest path problem. Given two node s and t, what is the length
of the shortest path between s and t?
Applications.
■Maze traversal.
■Erdős number.
■Fewest number of hops in a communication network.
12
Breadth First Search
s L1 L2 L n-1
BFS algorithm.
■L0 = { s }.
■L1 = all neighbors of L0.
■L2 = all nodes that do not belong to L0 or L1, and that have an edge
to a node in L1.
■Li+1 = all nodes that do not belong to an earlier layer, and that have
an edge to a node in Li.
13
Breadth First Search
Property. Let T be a BFS tree of G = (V, E), and let (x, y) be an edge of
G. Then the level of x and y differ by at most 1.
L1
L2
L3
14
BFS: Implementation with lists
15
Breadth First Search: Analysis
Pf.
■ Easy to prove O(n2) running time:
– at most n lists L[i]
– each node occurs on at most one list; for loop runs £ n times
– when we consider node u, there are £ n incident edges (u, v),
and we spend O(1) processing each edge
16
BFS: Implementation with a queue
17
BFS Implementation with a queue
18
Depth First Search: recursive implementation
Broken lines,
called “back edges”
connect nodes
one of which is
an ancestor of the
other. No cross edges.
19
DFS: Implementation with a stack
20
Connected Component
21
Connected Component
R
s
u v
22