SSSP in DAGs
(directed acyclic graphs)
• DFS (depth first search)
DFS(vertex v)
{
v.visited = TRUE;
for each w adjacent to v do
if(!w.visited) then dfs(w);
}
• If G=(V,E) not (strongly) connected then it may
have DFS forest
Topological Sort
Topological Sort: Ordering of vertices in a DAG
p
based on precedence : if path
then
vi
vj
before vj in ordering
ij
vi
– not unique:
– V V : indegree(v): #edges(u,v) E
– Can use DFS to obtain TS order
– Given directed graph G, is it a DAG?
• Can use TS to answer it ( cannot find vertex with indegree 0)
TS algorithm
• Output (number) v V with indegree 0
• (remove v and its outgoing edges)
• Repeat until no vertex left
TS algorithm
• How to find v V with indgree(v)=0
– Use queue:
• Each time incoming edge at u V is removed, decrease
indegree(u)
• If indegree(u) is 0, place u in queue
• O(|V|+|E|) time
– Init:
• Find v V with indegree(v)=0 in O(|V|) time
• Place in queue
DAG and TS
• Lemma 1: A DAG has a sink(outdegree=0) and
a source(indegree=0)
– Proof:
• Let P be the longest path in G,
• Claim: u is a source
p
u
v
– If not, (w,u). If w∉P => P’ = {(w,u)} U P is longer than P. If w
p => cycle:
• A similar argument shows v is a sink
Theorem 1: A directed G has a TS G is a DAG
• Proof:
– Assume G has TS and a cycle C. Let Vi C be the vertex with smallest
index assigned by TS. There is then an edge (Vj,Vi), with Vj C and j>I
=> contradiction with TS assignment.
Now Assume G acyclic. Use induction:
– Define P(n): a DAG with n vertices has a TS
– P(1) = true
Assume P(m) is true, Let G have m+1 vertices => source V0. G\{V0} has
TS V1 ,V2 ,…, Vm => G has TS V0 ,V1 ,…, Vm
SSSP in DAG (cont.)
• Use vertex selection rule: select in TS order
– SP well defined, even if negative weight edges (
negative weight cycle cannot exist)
DAG-SP(G,w,s)
Topologically sort vertices of G
Init-Single-Source ( G, s)
For each u ∈V, in TS order do
For each v ∈Adj[u] do
Relax(u,v,w)
– O(|V|+|E|) time
SSSP in DAG (cont.)
• Critical path in a DAG: longest path through
the DAG
– Can find one by:
• (1) negating edge weights and running DAG-SP, or
• (2) run DAG-SP with modifications:
– Replace “∞” by “- ∞” in init-single-source
– Replace “>” by “<“ in RELAX
– Note: Longest simple path in unweighted graph is
NP-Complete
BFS( breadth first search)
• Visit all nodes at same level before going to
next level; use queue for this
•
Queue_init();id=0;visited[u]=0, u V;
Bfs(v V){
enqueue(v);
While(!queue_empty()){
u=dequeue();visited[u]=++id; (need 3 values)
for each w adj[u] do
if(visited[w]==0){enqueue(w);visited[w]=-1}
}
}
How many levels in the queue at a time?
Application:Unweighted SPs
• δ(s,v) : #edges on the path (all edges have
weight 1)
• Use BFS: need min # edges to reach each u V
from s.
– Process vertices by layers:
• Process those that can be reached with1 edge
• Process those that can be reached with2 edge, etc.
– Use a queue:
• Check d[v]: if d[v]= ∞ , place in queue.
© Copyright 2026 Paperzz