Professional Documents
Culture Documents
Graph
• A graph is a structure that consists of a set of vertices
and a set of edges between pairs of vertices
Graph
• Example:
– V = {A, B, C, D, E}
– E = {(A,B), (A,D), (C,E), (D, E)}
Directed graph (digraph)
• Directed edge
– ordered pair of vertices (u,v)
• Undirected edge
– unordered pair of vertices (u,v)
Spanning subgraph
Connectivity
• A graph is connected if there is
a path between every pair of
vertices
• A connected component of a
graph G is a maximal
connected subgraph of G
Connected graph
Tree
• A forest is an undirected
graph without cycles
• The connected components
of a forest are trees
Forest
DAG
• A directed acyclic graph (DAG) is a digraph that has no
directed cycles
D E
B
C
A DAG G
Spanning Trees and Forests
Spanning tree
Representation of Graphs
Two standard ways:
• Adjacency List
– preferred for sparse graphs (|E| is much less than |V|^2)
– Unless otherwise specified we will assume this
representation
• Adjacency Matrix
– Preferred for dense graphs
Adjacency List
1 2 5
1
2 1 5 4
5 2 3 4
4 2 3 5
4 3 5 4 1 2
4 0 1 1 0 1
4 3 1 1 0 1 0
5
Graph Traversals
• For solving most problems on graphs
– Need to systematically visit all the vertices and edges of a graph
• Total: Θ(V+E)
BFS Tree
• predecessor pointers after BFS is completed define an
inverted tree
– Reverse edges: BFS tree rooted at s
– The edges of the BFS tree are called : tree edges
– Remaining graph edges are called: cross edges
BFS and shortest paths
• Theorem: Let G=(V,E) be a directed or undirected graph,
and suppose BFS is run on G starting from vertex s.
During its execution BFS discovers every vertex v in V
that is reachable from s. Let δ(s,v) denote the number of
edges on the shortest path form s to v. Upon termination
of BFS, d[v] = δ(s,v) for all v in V.
DFS
• Start at a source vertex s
• Search as far into the graph as possible and backtrack
when there is no new vertices to discover
– recursive
color[u] and pred[u] as before
• color[u]
– Undiscovered: white
– Discovered but not finished processing: gray
– Finished: black
• pred[u]
– Pointer to the vertex that first discovered u
Time stamps,
• We store two time stamps:
– d[u]: the time vertex u is first discovered (discovery time)
– f[u]: the time we finish processing vertex u (finish time)
DFS(G) DFS-VISIT(u)
for each (u in V) do //vertex u is just discovered
color[u] = white color[u] = gray
pred[u] = NIL time = time +1
time = 0 d[u] = time
for each (u in V) do for each (v in Adj[u]) do
if (color[u] == white) //explore neighbor v
DFS-VISIT(u) if (color[v] == white) then
//v is discovered by u
pred[v] = u
DFS-VISIT(v)
DFS-VISIT invoked by color[u] = black // u is finished
each vertex exactly
f[u] = time = time+ 1
once.
Θ(V+E)
DFS Forest
• Tree edges: inverse of pred[] pointers
– Recursion tree, where the edge
(u,v) arises when processing a
vertex u, we call DFS-VISIT(v)