L17 Elementary Graph Algo
L17 Elementary Graph Algo
Overview:
Definition of a graph
Representation of graphs
adjacency list
matrix
Elementary search algorithms
breadth-first search (BFS)
depth-first search(DFS)
topological sort
strongly connected components
Chapter 22 part 1: Fundamentals and Breadth-First search
Notation
|V| = # of vertices
|E| = # of edges
1
Breadth-first search: Given G(V,E) and a source vertex s,
Q 0, Enqueue(Q,s)
Runtime analysis:
initialization requires O(V).
each vertex is discovered at most once
queue operations require O(V).
searching adjacency lists requires O(E)
total runtime O(V+E)
Example of BFS (p596) using pseudo-code
Example of BFS (p596) using pseudo-code
Predecessor sub-graph
Gp(Vp,Ep)
Vp = {v V : p[v] NIL} {s}
Ep = {(p[v],v) : v Vp - {s}}
s t
v u
BFS by hand:
When a new vertex is discovered enter number one greater than the parent.
Resolve ambiguities about which adjacency list to search next by alphabetic order
Example: u can be discovered from either t or v. Choose t
Mark the edges used in a search with a T for tree edge. Keep a record of parentage.
s t
T
0 1
v u
BFS by hand:
With ambiguity resolved by alphabetical order, edge (t,u) becomes a
tree edge rather than (v,u)
s t
T
0 1
T T
1 2
v u
Finding shortest path is most common application of
Breadth-first search
If a vertex is reachable from the source, the integer in each vertex, d(s,a),
is the length in edges of the shortest path from the source.
s t
T
0 1
T T
1 2
v u
Weight of a path