Lec5 Handout
Lec5 Handout
22 February 2023
▶ O(m + n) time
▶ Check connectivity:
existence of path between two nodes
BFS: find shortest path
divide into connected components
▶ Bipartite testing
▶ Directed graphs
▶ Traversal
▶ Strong connectivity
▶ Topological sorting
Bipartite Graphs
Can color nodes red/blue s.t. no edges between nodes of same color.
Examples
▶ student-college graph in stable matching
▶ client-server connections
Bipartite Graphs and Odd Cycles
G = (V, E)
▶ (u, v) ∈ E is a directed edge
▶ u points to v
Examples
▶ Facebook: undirected
▶ Twitter: directed
▶ Web: directed
▶ Road network: directed (if one-way roads)
We may have both a u → v and a v → u edge
Directed Graph Definitions
Useful to keep adjacency lists for both outgoing and incoming edges.
Traversing Directed vs. Undirected Graphs
1
No longer true in directed graph:
2 3
BFS in Directed Graphs
1
1 7
2
2 3
3 4
4 5 8
5
6
6
A1
B2 C3
D4 E5
Univ. of X
My song
lyrics Strongly connected graph.
Classes USNews:
Directed path between any
College
Rankings two nodes.
I teach at
Networks
Univ. of X
Strongly connected
USNews:
Networks
Featured
Colleges
component (SCC).
class blog
Maximal subset of nodes
Blog post about
college rankings with directed path between
any two.
Blog post
Company Z's
about
Company Z
home page
SCCs can be found in time
Our Press
O(m + n). (Tarjan, 1972)
Founders Releases
Contact Us
Figure 13.6: A directed graph with its strongly connected components identified.
Directed Acyclic Graphs
Definition
A directed acyclic graph (DAG) is a directed graph with no cycles.
CS220
CS187 CS311
CS240
Math132 CS383
CS250
CS220
CS187 CS311
CS240
Math132 CS383
CS250
CS220
CS187 CS311
CS240
Math132 CS383
CS250
topo-sort(G)
while there are nodes remaining do
Find a node v with no incoming edges
Place v next in the order
Delete v and all of its outgoing edges from G
topo-sort(G)
while there are nodes remaining do ▷ n iterations
Find a node v with no incoming edges ▷ O(n)/iteration?
Place v next in the order ▷ O(1)/iteration
Delete v and its outgoing edges from G ▷ O(m) overall
Optimization: don’t search every time for nodes w/o incoming edges
▶ Keep and update incoming edge count for each node:
setup in O(m + n), each update constant-time
▶ Keep set of nodes with no incoming edges;
add node to set when its count becomes zero
▶ Running time: O(m + n)