Elementary Graph Algorithms: 1 Graphs
Elementary Graph Algorithms: 1 Graphs
CSE 680
1 Graphs
• G(V, E) — V : vertex set; E: edge set.
• No self-loops.
• Length of path: either the number of edges in the path or the total
weight.
• Acyclic graph
• Graph representations
– Adjacency matrix
– Adjacency lists
1
2 Basic Depth-First Search
procedure Search(G = (V, E))
// Assume V = {1, 2, . . . , n} //
// global array visited[1..n] //
visited[1..n] ← 0;
for i ← 1 to n
if visited[i] = 0 then call df s(i)
procedure df s(v)
visited[v] ← 1;
for each node w such that (v, w) ∈ E do
if visited[w] = 0 then call df s(w)
• In the entire depth frist search, how many times in total is df s() called?
• In the entire depth frist search, how many times in total is the “if
visited[w] = 0” part of the “if visited[w] = 0 then call df s(w)” state-
ment executed?
• Time complexity
2
3 Connectivity
• An undirected graph is connected if every pair of vertices are connected
by a path.
3
4 Bipartite Graph
• Definition: An undirected graph G(V, E) is said to be bipartite if V can
be divided into two sets V1 and V2 such that all edges in G go between
V1 and V2 .
procedure df s(v, c)
visited[v] ← c;
for each node w such that (v, w) ∈ E do
if visited[w] = 0 then call df s(w, −c)
elseif visited[w] = c then f lag ← f alse;
4
5 Advanced Depth-First Search
procedure Search(G = (V, E))
// Assume V = {1, 2, . . . , n} //
time ← 0;
vn[1..n] ← 0; /* vn stands for visit number */
for i ← 1 to n
if vn[i] = 0 then call df s(i)
procedure df s(v)
vn[v] ← time ← time + 1;
for each node w such that (v, w) ∈ E do
if vn[w] = 0 then call df s(w);
f n[v] ← time ← time + 1 /* f n stands for finish number */
5
6 Topological Sort
• Problem: given a directed graph G = (V, E), sort the vertices into a
linear list such that for every edge (u, v) ∈ E, u is ahead of v in the
list.
• Algorithm:
6
7 Strongly Connected Components
• A directed graph is strongly connected if for every two nodes u and v
there is a path from u to v and one from v to u.
where {df s(v) on G} denotes the set of all vertices visited during df s(v)
on G.
7
• Algorithm:
visited[1..n] ← 0
for each vertex u in decreasing order of f n[u] do
if visited[u] = 0 then call df s(u)