Algorithm Exam Help
Algorithm Exam Help
Graph Problems
• Graph reachability by BFS or DFS in O(|E|) time
• Graph exploration/connected components via Full-BFS or Full-DFS
• Topological sort / Cycle detection via DFS
• Negative-weight cycle detection via Bellman-Ford
• Single Source Shortest Paths (SSSP)
Restrictions SSSP
Algorithm
Graph Weights Name Running Time
O(·)
DAG Any DAG |V | + |E|
Relaxation |V | + |E|
General Unweighted BFS
General Non- Dijkstra |V | log |V | + |
negative Bellman-Ford E|
General Any |V | · |E|
Problem 2. Unicycles
Problem 3. Doh!-nut
Momer has just finished work at the FingSprield power plant at
location p, and needs to drive to his home at location h. But along the
way, if his driving route ever comes within driving distance k of a
doughnut shop, he will stop and eat doughnuts, and his wife, Harge,
will be angry. Momer knows the layout of Fing Sprield, which can be
modeled as a set of n locations, with two-way roads of known driving
distance connecting some pairs of locations (you may assume that no
location is incident to more than five roads), as well as the locations
of the d doughnut shops in the city. Describe an O(n log n)-time
algorithm to find the shortest driving route from the power plant back
home that avoids driving within driving distance k of a doughnut shop
(or determine no such route exists).
Solution: Construct a graph G with a vertex for each of the n city
locations, and an undirected edge between two locations if there is a
road connecting them, with each edge weighted by the positive length
of its corresponding road. The degree of each vertex is bounded by a
constant (i.e., 5), so the number of edges in G is O(n). First, we
identify vertices that are within driving distance k of a doughnut shop
location: create an auxiliary vertex x with a 0-weight outgoing edge
from x to every doughnut shop location, and run Dijkstra from x.
Remove every vertex from the graph whose shortest path from x is
less
Solution: Our strategy will compute intermediate values for each vertex
v∈V:
1. the minimum weight w1(v) of any path from s to v using exactly |V
| edges, and then
2. the minimum weight w2(v) of any path from v to t using any
number of edges.
First, to compute (1), we make a duplicated graph similar to Bellman-
Ford, but without edges corresponding to remaining at a vertex.
Specifically, construct a graph G1 with
|V | + 1 vertices for each vertex v ∈ V : vertex vk for k ∈ {0, . . . , |
V |} representing reaching
v from s along a path containing k edges; and
• |V | edges for each edge (u, v) ∈ E: edge (uk−1, vk ) of the same
weight for k ∈ {1, . . . , |V |}.