PDSA Interactive Book
Week 5

Graph Algorithms (Continued)

Directed graphs, ordering tasks, and the cheapest way to get from A to B.

After this chapter you can…
  • detect a directed cycle with DFS
  • compute a topological order two ways
  • find longest paths in a DAG
  • trace Dijkstra and say when it fails
  • choose between BFS, Dijkstra, Bellman–Ford and Floyd–Warshall

Directed graphs

In a directed graph, edges have a direction: u → v does not imply v → u. Everything from last week still works (adjacency lists store out-neighbours), but the questions change:

UndirectedDirected
connectedstrongly connected: every vertex reaches every other along directed paths
cycle: any closed loopdirected cycle: follows edge directions
degreein-degree and out-degree

A directed graph with no directed cycle is a DAG (directed acyclic graph). DAGs describe dependencies: course prerequisites, tasks in a project, build systems, spreadsheet formulas.

Detecting a directed cycle with DFS

Run DFS and keep three states per vertex: unvisited, in progress (on the current recursion stack), finished. If we ever meet an in-progress vertex, we have walked around a cycle.

Python · editable
Expected output: False True
Check yourself

In DFS on a directed graph, reaching a vertex that is currently on the recursion stack means…

Topological sort

A topological order lists every vertex so that for every edge u → v, u comes before v. It exists if and only if the graph is a DAG. It tells you a valid order for doing dependent tasks.

Method 1 — Kahn's algorithm (in-degrees)

Vertices with in-degree 0 have no unmet prerequisites. Output one, 'delete' it by decrementing the in-degree of its out-neighbours, and repeat. If we get stuck with vertices left over, a cycle exists.

Python · editable
Expected output: [0, 1, 3, 4, 2, 5, 6, 7]
Topological sort (Kahn) — in-degrees update as vertices leaveInteractive

Method 2 — reverse DFS finish order

Run DFS over all vertices. A vertex finishes only after all vertices reachable from it have finished. So listing vertices in decreasing finish time gives a topological order.

Python · editable
Expected output: [1, 0, 4, 3, 2, 5, 6, 7]
Many valid answers

A DAG usually has several topological orders — the two methods may print different ones, and both are correct. Check by verifying every edge goes left to right.

Check yourself

A graph has 5 vertices and the edges A→B, B→C, C→A, C→D, D→E. Does it have a topological order?

Predict the output

Which vertices does Kahn's algorithm start with?

adj = {'shirt': ['tie', 'belt'], 'tie': ['jacket'], 'belt': ['jacket'], 'trousers': ['belt', 'shoes'], 'socks': ['shoes'], 'jacket': [], 'shoes': []}
indeg = {v: 0 for v in adj}
for u in adj:
    for v in adj[u]:
        indeg[v] += 1
print([v for v in adj if indeg[v] == 0])
Check yourself

Kahn's algorithm outputs fewer than n vertices before the queue empties. This indicates…

Longest paths in a DAG

Longest path is NP-hard in general graphs, but in a DAG it is easy: process vertices in topological order, and for each vertex v compute L[v] = 1 + max(L[u] for edges u → v). This gives the critical path of a project: the minimum possible completion time even with unlimited workers.

Python · editable
Expected output: {0: 0, 1: 0, 2: 1, 3: 1, 4: 1, 5: 2, 6: 3, 7: 4} longest path has 4 edges
Why topological order helps

When we process v, all its predecessors are already done, so L[v] is final. This 'compute in dependency order' pattern is the seed of dynamic programming (Week 9).

Check yourself

Time to compute longest path in a DAG with n vertices and m edges?

Shortest paths: Dijkstra's algorithm

BFS counts edges. With weights (distances, times, costs) the path with fewest edges is not necessarily the cheapest. Dijkstra's algorithm finds the cheapest path from a source s to all vertices, provided no edge weight is negative.

Idea

Maintain a tentative distance d[v] (initially ∞, with d[s] = 0). Repeatedly pick the unfinalised vertex with the smallest tentative distance — its distance is now final — and relax its outgoing edges: if d[u] + w < d[v] then update d[v].

Why it is correct

Take the unfinalised vertex u with the smallest d[u]. Any other route to u must leave the finalised set through some other unfinalised vertex whose tentative distance is already ≥ d[u], and adding non-negative weights cannot make it shorter. So d[u] is the true distance.

Python · editable
Expected output: [0, 10, 16, 86, 30, 80, 35] [None, 0, 1, 2, 1, 4, 4]
Dijkstra — pick the closest vertex, then relax its edgesInteractive

Your turn. Build a weighted directed graph (use “Set weight” to change costs) and run Dijkstra from any vertex. Switch the algorithm to Topological sort, press “🎲 Random” for an acyclic graph, then add one edge backwards to create a cycle and watch Kahn's algorithm get stuck.

Graph lab — Dijkstra and topological sort on your own digraphInteractive

Running time

With the simple scan above: n rounds × O(n) to pick the minimum + O(m) relaxations = O(n²). Using a priority queue (heap) to pick the minimum in O(log n) makes it O((n + m) log n), much better for sparse graphs — we build heaps in Week 6.

Python · editable
Expected output: {0: 0, 1: 10, 2: 16, 3: 86, 4: 30, 5: 80, 6: 35}
Negative weights break Dijkstra

Suppose s→a costs 2, s→b costs 3 and b→a costs −5. Dijkstra finalises a with distance 2, but the true shortest route is s→b→a = −2. Greedy finalisation assumes later detours cannot help; negative edges violate that.

Predict the output

What are the shortest distances from vertex 0?

INF = float("inf")
adj = {0: [(1, 4), (2, 1)], 1: [(3, 1)], 2: [(1, 2), (3, 5)], 3: []}
d = {v: INF for v in adj}
d[0] = 0
for _ in range(len(adj)):
    for u in adj:
        for v, w in adj[u]:
            if d[u] + w < d[v]:
                d[v] = d[u] + w
print(d)
Check yourself

Why does BFS give wrong answers for weighted shortest paths?

Check yourself

In the visualised graph, what is the shortest distance from vertex 0 to vertex 4? (Run Dijkstra or the code above.)

Negative weights: Bellman–Ford and Floyd–Warshall

Bellman–Ford handles negative edges (but not a negative cycle, where distances would decrease forever). A shortest path has at most n − 1 edges, so relaxing every edge n − 1 times is enough. If a further round still improves something, a negative cycle exists. Time: O(n·m).

Python · editable
Expected output: ([0, -2, 3, 2], False)

Floyd–Warshall answers all-pairs shortest paths. Let D[i][j] be the best known distance. For each possible intermediate vertex k in turn, test whether going i → k → j beats going directly. Three nested loops: O(n³).

Python · editable
Expected output: [0, 3, 5, 6] [5, 0, 2, 3] [3, 6, 0, 1] [2, 5, 7, 0]
AlgorithmHandlesTime
BFSunweighted, single sourceO(n + m)
Dijkstra (heap)non-negative weights, single sourceO((n + m) log n)
Bellman–Fordnegative weights, single sourceO(n·m)
Floyd–Warshallall pairs, negative weights (no neg. cycle)O(n³)
DAG relaxationany weights, DAG only, single sourceO(n + m)
Check yourself

You need shortest paths from one source on a graph that may contain negative edge weights (but no negative cycle). Use…

Check yourself

Floyd–Warshall's three nested loops make it…

Chapter challenge — Week 5

…
Check yourself

Which graphs have a topological order?

Predict the output

What does this program print?

adj = {'a': ['b', 'c'], 'b': ['d'], 'c': ['d'], 'd': []}
seen, fin = set(), []
def go(u):
    seen.add(u)
    for v in adj[u]:
        if v not in seen:
            go(v)
    fin.append(u)
go('a')
print(fin[::-1])
Put in order

Put Dijkstra's loop in order.

Predict the output

What does this print? (type the exact output)

INF = 10**9
D = [[0, 4, 9], [INF, 0, 3], [INF, INF, 0]]
for k in range(3):
    for i in range(3):
        for j in range(3):
            D[i][j] = min(D[i][j], D[i][k] + D[k][j])
print(D[0][2])
Check yourself

Pick all correct statements.

Check yourself

A project has tasks with dependencies, and each takes one day; with unlimited helpers, the minimum days = ?

Check yourself

Kahn's algorithm processes a DAG with 6 vertices. How many vertices are output if the graph is a DAG?

Check yourself

Using a heap, Dijkstra's running time becomes…

Practice on LeetCode

Directed graphs, topological order and weighted shortest paths.

How to practise

Try each problem first with a brute-force idea and estimate its cost, then improve it using this chapter's technique. Links open LeetCode in a new tab; all problems listed are free. Levels follow LeetCode's own labels.

0 / 9 solvedTick a problem when you have solved it — saved in this browser.
ProblemLevelPractises
Course Schedule ↗Mediumcycle detection / Kahn's algorithm
Course Schedule II ↗Mediumoutput a topological order
Find Eventual Safe States ↗MediumDFS with three states, or reverse Kahn
Network Delay Time ↗MediumDijkstra
Path with Maximum Probability ↗MediumDijkstra variant
Path With Minimum Effort ↗MediumDijkstra on a grid with a different cost
Cheapest Flights Within K Stops ↗MediumBellman–Ford with a limit on rounds
Find the City With the Smallest Number of Neighbors at a Threshold Distance ↗MediumFloyd–Warshall
Longest Increasing Path in a Matrix ↗Hardlongest path in a DAG (memoised DFS)

Key takeaways

  • A DAG has no directed cycle; a topological order exists iff the graph is a DAG, and can be found in O(n + m) with Kahn's algorithm or reverse DFS finish order.
  • Longest paths in a DAG are easy: process in topological order (the first taste of dynamic programming).
  • Dijkstra: greedy, picks the closest unfinished vertex then relaxes edges; needs non-negative weights; O(n²) simple, O((n + m) log n) with a heap.
  • Bellman–Ford handles negative edges in O(nm); Floyd–Warshall gives all-pairs distances in O(n³).

PDSA Interactive Book · Programming, Data Structures and Algorithms using Python (BSCS2002), IIT Madras BS Degree Programme.
Created by Ammar Hashmi · © 2026. An unofficial study companion — the syllabus follows the official course page and the examples are built around the PDSA Online Textbook; lectures by Prof. Madhavan Mukund (CMI). Always cross-check with the official course material.
Found a mistake or have a suggestion? Report it on GitHub ↗ · Press / to search.