Week 11: Shortest Paths, Transitive Closure & Matrix Powers

3517 words
18 min read
2026-09-12T00:00:00.000Z
Python Week 1: the first filter for runtime behavior
Visual companion
Python
Type and operator map

Python Week 1: the first filter for runtime behavior

View
Revision summary

What this note is really saying

Short form

Weighted graphs, relaxation, Dijkstra, Bellman-Ford, negative cycles, DAG longest paths, and adjacency matrix powers. # Mathematics I — Week 11: Shortest Paths, Transitive Closure & Matrix Powers IITM’s Week 11 covers **longest path, transitive closure, matrix multiplication in graph settings, and single-source shor...

Mathematics I — Week 11: Shortest Paths, Transitive Closure & Matrix Powers

IITM’s Week 11 covers longest path, transitive closure, matrix multiplication in graph settings, and single-source shortest paths including Dijkstra’s and Bellman–Ford algorithms.

TL;DR

Week 10 taught how to traverse graphs.
Week 11 asks:
How do we compute richer path information?
The main ideas are:
  • shortest path vs longest path
  • weighted graphs
  • DAG longest path intuition
  • reachability
  • transitive closure
  • adjacency matrices and matrix powers
  • single-source shortest path
  • Dijkstra’s algorithm
  • Bellman–Ford algorithm
  • negative edge weights

1. Weighted graphs

A weighted graph assigns a numerical value to each edge.
Example:
text
A --5-- B --2-- C
 \      |
  9     1
   \    |
     D
Weights might represent:
  • distance
  • time
  • cost
  • probability-related score
  • energy
  • latency
Formally, an edge may have weight:
w(u,v).w(u,v).

2. Path weight

For a path:
v0→v1→⋯→vk,v_0\to v_1\to \cdots \to v_k,
its total weight is:
∑i=0k−1w(vi,vi+1)\boxed{ \sum_{i=0}^{k-1} w(v_i,v_{i+1}) }
Example:
If:
A→BA\to B
has weight 44, and:
B→CB\to C
has weight 77,
then path:
A→B→CA\to B\to C
has total weight:
4+7=11.4+7=11.

3. Shortest-path problem

Given two vertices ss and tt:
Find a path from ss to tt with minimum total weight.
For unweighted graphs, BFS solves this when each edge effectively has equal cost.
For weighted graphs, we need algorithms like:
  • Dijkstra
  • Bellman–Ford

4. Single-source shortest path

Instead of solving for one target, we often ask:
From one source ss, find shortest distances to every reachable vertex.
This is the single-source shortest-path problem, often abbreviated SSSP.
Output:
d[v]d[v]
for every vertex vv, where:
d[v]d[v]
is shortest known distance from source ss to vv.

5. Relaxation — the core idea

Most shortest-path algorithms repeatedly perform relaxation.
Suppose we know:
d[u]d[u]
and have edge:
u→vu\to v
with weight:
w(u,v).w(u,v).
If:
d[u]+w(u,v)<d[v],d[u]+w(u,v)<d[v],
then update:
d[v]=d[u]+w(u,v)\boxed{ d[v]=d[u]+w(u,v) }
and often:
parent[v]=u.parent[v]=u.
This means:
We found a cheaper route to vv through uu.

6. Example of relaxation

Suppose:
d[A]=5d[A]=5
and:
A→BA\to B
has weight:
3.3.
Current:
d[B]=12.d[B]=12.
Going through AA gives:
5+3=8.5+3=8.
Since:
8<12,8<12,
we update:
d[B]=8\boxed{d[B]=8}

7. Initial shortest-path setup

For source:
s,s,
initialize:
d[s]=0.d[s]=0.
For every other vertex:
d[v]=∞.d[v]=\infty.
Why infinity?
Because initially we know no path to those vertices.
Then relax edges to improve estimates.

8. Dijkstra’s algorithm

Dijkstra solves single-source shortest paths when edge weights are nonnegative.
Core idea:
Repeatedly finalize the currently closest unprocessed vertex.
It is a greedy algorithm.

9. Dijkstra intuition

Suppose source is AA.
At every step:
  1. choose unvisited vertex with smallest current distance
  2. finalize it
  3. relax all outgoing edges
  4. repeat
Once a vertex is finalized, its shortest distance is guaranteed correct — provided all edge weights are nonnegative.

10. Dijkstra example

Consider:
text
A --4--> B
|        |
1        1
v        v
C --2--> D
Source:
A.A.
Initialize:
d[A]=0d[A]=0 d[B]=d[C]=d[D]=∞.d[B]=d[C]=d[D]=\infty.
From AA:
d[B]=4d[B]=4 d[C]=1.d[C]=1.
Choose smallest unvisited:
CC
with distance:
1.1.
Relax:
C→DC\to D
weight 22:
d[D]=1+2=3.d[D]=1+2=3.
Now smallest is:
D=3.D=3.
Then:
B=4.B=4.
So final shortest distances:
d[A]=0,d[C]=1,d[D]=3,d[B]=4\boxed{ d[A]=0,\quad d[C]=1,\quad d[D]=3,\quad d[B]=4 }

11. Why Dijkstra works

The greedy step relies on:
w(e)≥0.w(e)\geq0.
If we already selected the vertex with smallest tentative distance, no future path through unprocessed vertices can make it smaller using nonnegative edges.
That guarantee breaks with negative weights.

12. Negative-weight problem

Suppose:
text
A --2--> B
|        ^
5        |
v       -10
C ------- 
Initially Dijkstra may think:
d[B]=2.d[B]=2.
But path:
A→C→BA\to C\to B
costs:
5+(−10)=−5.5+(-10)=-5.
So a later negative edge can improve a vertex that seemed already finalized.
That breaks Dijkstra's logic.

13. Dijkstra restriction

You should memorize:
Dijkstra requires nonnegative edge weights\boxed{ \text{Dijkstra requires nonnegative edge weights} }
Zero-weight edges are fine.
Negative edges are not.

14. Dijkstra pseudocode intuition

text
dist[source] = 0
all others = infinity

while unprocessed vertices remain:
    choose u with smallest dist[u]
    mark u processed

    for each edge u -> v:
        if dist[u] + w(u,v) < dist[v]:
            update dist[v]
Efficient implementations typically use a priority queue.

15. Dijkstra complexity

With a binary heap / priority queue:
O((V+E)log⁡V)\boxed{ O((V+E)\log V) }
often simplified to:
O(Elog⁡V)O(E\log V)
for connected sparse graphs.
A simpler array/matrix implementation may be:
O(V2).O(V^2).
For exam purposes, context matters.

16. Bellman–Ford algorithm

Bellman–Ford also solves single-source shortest paths.
But unlike Dijkstra, it can handle:
negative edge weights\boxed{\text{negative edge weights}}
as long as there is no reachable negative-weight cycle that makes shortest paths undefined.

17. Bellman–Ford core idea

Instead of greedily finalizing vertices, Bellman–Ford repeatedly relaxes all edges.
For a graph with:
∣V∣=n,|V|=n,
repeat edge relaxation:
n−1n-1
times.
Why?
Any simple path can contain at most:
n−1n-1
edges.

18. Bellman–Ford procedure

Initialize:
d[s]=0d[s]=0
and all others infinity.
Then:
text
repeat |V|-1 times:
    for every edge (u,v):
        relax(u,v)
After that, one additional pass can test for negative cycles.

19. Why ∣V∣−1|V|-1 iterations?

A shortest simple path cannot repeat a vertex.
If it repeated a vertex, that contains a cycle.
A simple path on ∣V∣|V| vertices uses at most:
∣V∣−1|V|-1
edges.
After the first relaxation round, shortest paths of at most one edge can propagate.
After two rounds, two-edge paths.
Eventually:
∣V∣−1|V|-1
edges are enough.

20. Bellman–Ford example

Suppose:
text
S --4--> A
|        |
5       -2
v        v
B --1--> C
There may be alternative routes.
Bellman–Ford repeatedly examines all edges and improves estimates whenever possible.
The important conceptual point is:
improvements are allowed even if a vertex was already improved before.
Nothing is permanently finalized too early.

21. Negative cycles

A negative cycle is a directed cycle whose total weight is negative.
Example:
A→BA\to B
weight 22
B→CB\to C
weight −5-5
C→AC\to A
weight 11
Total:
2−5+1=−2.2-5+1=-2.

22. Why negative cycles break shortest paths

Suppose a path can reach a negative cycle.
You could traverse that cycle repeatedly:
−2,−4,−6,−8,…-2,-4,-6,-8,\dots
making path cost arbitrarily small.
So there is no finite "shortest" path.
Mathematically:
shortest distance=−∞\boxed{ \text{shortest distance}=-\infty }
in the limiting sense.

23. Detecting negative cycles with Bellman–Ford

After:
∣V∣−1|V|-1
full relaxation rounds, perform one more.
If any distance can still decrease, then:
reachable negative cycle exists\boxed{ \text{reachable negative cycle exists} }
This is a major advantage of Bellman–Ford.

24. Bellman–Ford complexity

Bellman–Ford scans all EE edges for roughly VV rounds.
Therefore:
O(VE)\boxed{ O(VE) }
This is slower than Dijkstra on ordinary nonnegative graphs.

25. Dijkstra vs Bellman–Ford

DijkstraBellman–Ford
greedyrepeated relaxation
nonnegative weightsnegative weights allowed
fasterslower
usually priority queuescan all edges
cannot detect negative cycles properlycan detect reachable negative cycles
High-value rule:
Negative edges? Think Bellman–Ford.\boxed{ \text{Negative edges? Think Bellman–Ford.} }

26. BFS vs Dijkstra

BFS can be viewed as a special shortest-path algorithm where every edge has identical weight:
1.1.
So:

Unweighted / equal-weight graph

Use BFS.

Nonnegative weighted graph

Use Dijkstra.

Negative weights

Use Bellman–Ford.
This taxonomy is worth memorizing.

27. Shortest-path algorithm decision table

GraphPreferred basic algorithm
unweightedBFS
weighted, all weights ≥0\geq0Dijkstra
negative weights, no problematic negative cycleBellman–Ford
DAGtopological-order dynamic programming can be even simpler

28. Longest-path problem

Now reverse the goal:
Find a path with maximum total weight or maximum number of edges.
This sounds like simply modifying shortest path.
Unfortunately, in general graphs, longest path is much harder.

29. Why arbitrary longest path is difficult

If cycles are allowed, you can potentially keep looping.
Even when restricting to simple paths, the general longest-path problem is computationally difficult.
But on a DAG, the problem becomes manageable.
This is why DAGs from Week 10 matter.

30. Longest path in a DAG

Because a DAG has no cycles, vertices can be arranged in topological order.
Then compute longest distances in that order.
Conceptually:
d[v]=max⁡u→v(d[u]+w(u,v))\boxed{ d[v] = \max_{u\to v} \left(d[u]+w(u,v)\right) }
This resembles shortest-path relaxation, but uses:
max⁡\max
instead of:
min⁡.\min.

31. Example DAG

text
A → B → D
 \      ↑
  → C ──
Suppose weights:
A→B=2A\to B=2 A→C=5A\to C=5 B→D=4B\to D=4 C→D=3.C\to D=3.
Possible paths to DD:
A→B→D:2+4=6A\to B\to D: \quad2+4=6 A→C→D:5+3=8.A\to C\to D: \quad5+3=8.
So longest path from AA to DD has weight:
8\boxed{8}

32. Longest path as scheduling

A DAG may represent tasks:
text
A → B → D
 \→ C ─→
Suppose edge/node weights represent durations.
The longest dependency chain determines the critical path.
This is important in:
  • project scheduling
  • build systems
  • dependency planning
  • workflow optimization

33. Reachability

A vertex:
vv
is reachable from:
uu
if there exists a directed path:
u⇝v.u\leadsto v.
We often want to know reachability for every pair of vertices.
That leads to transitive closure.

34. Transitive closure

The transitive closure of a directed graph adds an edge:
u→vu\to v
whenever vv is reachable from uu.
So it converts:
path exists
into:
direct relation in the closure.

35. Example

Original:
text
A → B → C
Since:
A⇝C,A\leadsto C,
the transitive closure also contains:
A→C.A\to C.
Closure:
text
A → B → C
 \------→

36. Relation-theory connection

Recall Week 1 transitivity:
aRbaRb
and:
bRcbRc
implies:
aRc.aRc.
Transitive closure means:
Add the minimum required relationships so the relation becomes transitive.
So Week 11 reconnects directly to Week 1.

37. Reachability matrix

For vertices:
v1,…,vn,v_1,\dots,v_n,
define matrix:
RR
where:
Rij={1,vj reachable from vi0,otherwiseR_{ij}= \begin{cases} 1,&v_j\text{ reachable from }v_i\\ 0,&\text{otherwise} \end{cases}
This is essentially an adjacency matrix of the transitive closure.

38. Adjacency matrix recap

For graph GG, adjacency matrix:
Aij=1A_{ij}=1
if edge:
i→ji\to j
exists.
Otherwise:
Aij=0.A_{ij}=0.
Matrix multiplication reveals deeper path information.

39. Why A2A^2 is interesting

Consider:
(A2)ij.(A^2)_{ij}.
By matrix multiplication:
(A2)ij=∑kAikAkj.(A^2)_{ij} = \sum_k A_{ik}A_{kj}.
Each term:
AikAkjA_{ik}A_{kj}
equals 11 exactly when:
i→ki\to k
and:
k→j.k\to j.
Therefore:
(A2)ij\boxed{ (A^2)_{ij} }
counts walks of length:
22
from ii to jj.

40. General matrix-power interpretation

More generally:
(Ak)ij\boxed{ (A^k)_{ij} }
counts the number of walks of length:
kk
from vertex ii to vertex jj.
This is a major connection between linear algebra and graph theory.

41. Example

Suppose:
text
A → B → C
Adjacency matrix in order A,B,CA,B,C:
A=(010001000).A= \begin{pmatrix} 0&1&0\\ 0&0&1\\ 0&0&0 \end{pmatrix}.
Then:
A2=(001000000).A^2= \begin{pmatrix} 0&0&1\\ 0&0&0\\ 0&0&0 \end{pmatrix}.
The 11 in position (A,C)(A,C) indicates one walk of length 22:
A→B→C.A\to B\to C.

42. Reachability from matrix powers

A path between distinct vertices can have length at most:
∣V∣−1|V|-1
if considering a simple path.
So reachability information is related to:
A+A2+⋯+An−1.A+A^2+\cdots+A^{n-1}.
If the (i,j)(i,j) entry is nonzero somewhere in these powers, then:
jj
is reachable from:
i.i.
For Boolean reachability, we care about existence, not count.

43. Boolean matrix viewpoint

Instead of ordinary arithmetic:
  • multiplication behaves like AND
  • addition behaves like OR
Then matrix multiplication can directly encode reachability.
This is sometimes called Boolean matrix multiplication.
Conceptually:
1∧1=11\land1=1
means both required edges exist.
And:
1∨1=11\lor1=1
means at least one path exists.

44. Transitive closure via repeated paths

One conceptual formula is:
R=I∨A∨A2∨⋯R = I\lor A\lor A^2\lor\cdots
depending on whether self-reachability is included.
Here:
II
represents length-00 paths:
v⇝v.v\leadsto v.
The exact convention may vary, so check whether the relation is defined reflexively.

45. Matrix multiplication definition

For:
A∈Rm×nA\in\mathbb R^{m\times n}
and:
B∈Rn×p,B\in\mathbb R^{n\times p},
the product:
C=ABC=AB
has size:
m×p.m\times p.
Each entry:
Cij=∑k=1nAikBkj\boxed{ C_{ij} = \sum_{k=1}^n A_{ik}B_{kj} }
Graph applications rely heavily on this formula.

46. Matrix-dimension rule

If:
AA
is:
m×nm\times n
and:
BB
is:
r×p,r\times p,
then:
ABAB
exists only when:
n=r.\boxed{n=r}.
Result size:
m×p.\boxed{m\times p}.

47. Matrix multiplication is not commutative

In general:
AB≠BA\boxed{ AB\neq BA }
and one product may exist when the reverse doesn't.
This matters because directed graph structure itself is order-sensitive.

48. Path reconstruction in shortest-path algorithms

Distances tell us cost.
To recover the actual path, maintain:
parent[v].parent[v].
Whenever relaxation improves:
d[v],d[v],
set:
parent[v]=u.parent[v]=u.
Then trace backward from target.

49. Example

Suppose final parents are:
parent[D]=Cparent[D]=C parent[C]=Bparent[C]=B parent[B]=A.parent[B]=A.
Then path to DD backwards:
D←C←B←A.D\leftarrow C\leftarrow B\leftarrow A.
Reverse:
A→B→C→D\boxed{ A\to B\to C\to D }

50. Triangle inequality intuition for shortest paths

Shortest-path distances satisfy:
d(s,v)≤d(s,u)+w(u,v)\boxed{ d(s,v) \leq d(s,u)+w(u,v) }
If the inequality is violated by our current estimates, relaxation fixes it.
So relaxation is repeatedly enforcing shortest-path consistency.

51. Dijkstra full small example

Consider:
text
S --2--> A --3--> C
|        |
5        1
v        v
B --1--> C
Source:
S.S.
Initialize:
d[S]=0d[S]=0
others infinity.
From SS:
d[A]=2d[A]=2 d[B]=5.d[B]=5.
Choose AA:
2.2.
Relax:
A→C:2+3=5.A\to C: \quad2+3=5.
So:
d[C]=5.d[C]=5.
Suppose:
A→BA\to B
has weight 11.
Then:
2+1=3<5.2+1=3<5.
Update:
d[B]=3.d[B]=3.
Choose BB next:
3.3.
Relax:
B→CB\to C
weight 11:
3+1=4<5.3+1=4<5.
So:
d[C]=4.d[C]=4.
Final:
d[S]=0,d[A]=2,d[B]=3,d[C]=4\boxed{ d[S]=0,\quad d[A]=2,\quad d[B]=3,\quad d[C]=4 }

52. Why greedy order mattered

Dijkstra processes:
S→A→B→CS\to A\to B\to C
based on smallest tentative distance, not alphabetical order or graph depth.
This is a common misunderstanding.

Common mistake: Dijkstra with negative edges
Do not.
Even one negative edge can invalidate its finalized-distance assumption.
Use Bellman–Ford or another appropriate method.

Common mistake: Bellman–Ford needs all cycles absent
No.
Bellman–Ford can work with cycles.
The problem is a reachable:
negative-weight cycle\boxed{\text{negative-weight cycle}}
not cycles in general.
Positive or zero-weight cycles are fine for shortest-path existence.

Common mistake: negative edge = negative cycle
These are different.
A graph may contain a negative edge but no negative cycle.
Example:
text
A --(-3)--> B → C
No return route means no cycle.
Bellman–Ford can still compute shortest paths.

Common mistake: longest path = negate weights + Dijkstra
Not generally.
Negating weights creates negative edges, which Dijkstra cannot handle.
And arbitrary longest simple paths are fundamentally harder.
On DAGs, use topological structure.

Common mistake: adjacency matrix power counts simple paths
Not necessarily.
(Ak)ij(A^k)_{ij}
counts walks of length kk.
Walks may repeat vertices and edges.
That is different from simple paths.

Common mistake: transitive closure stores distance
No.
Transitive closure answers:
reachable or not?\boxed{\text{reachable or not?}}
It doesn't inherently store:
  • shortest distance
  • number of paths
  • path weight
Those are different graph problems.

Common mistake: shortest path means fewest edges
Only in unweighted/equal-weight graphs.
Weighted shortest path minimizes:
total edge weight\boxed{\text{total edge weight}}
A path with more edges can still be cheaper.

60. Example

Path 1:
A→BA\to B
one edge of weight:
100.100.
Path 2:
A→C→D→BA\to C\to D\to B
three edges of weights:
1+1+1=3.1+1+1=3.
Weighted shortest path is Path 2.

61. Algorithm selection mental map

text
Need shortest path?
│
├── unweighted / equal weights
│      └── BFS
│
├── weighted and all weights >= 0
│      └── Dijkstra
│
├── negative weights possible
│      └── Bellman–Ford
│
└── DAG
       └── topological-order DP
This is extremely useful for exam reasoning.

62. Week 11 formula/fact sheet

Relaxation

d[v]←min⁡(d[v],d[u]+w(u,v))\boxed{ d[v]\leftarrow \min(d[v],d[u]+w(u,v)) }

Dijkstra condition

w(e)≥0\boxed{ w(e)\geq0 }

Bellman–Ford rounds

∣V∣−1\boxed{ |V|-1 }

Bellman–Ford complexity

O(VE)\boxed{ O(VE) }

Adjacency powers

(Ak)ij=number of length-k walks from i to j\boxed{ (A^k)_{ij} = \text{number of length-}k\text{ walks from }i\text{ to }j }

DAG longest-path recurrence

d[v]=max⁡u→v(d[u]+w(u,v))\boxed{ d[v] = \max_{u\to v} (d[u]+w(u,v)) }

63. Week 11 conceptual map

text
Weighted Graphs
│
├── path weight
├── relaxation
│
├── shortest paths
│   ├── BFS
│   ├── Dijkstra
│   └── Bellman–Ford
│
├── longest path
│   └── tractable on DAGs
│
├── reachability
│   └── transitive closure
│
└── adjacency matrix
    └── A^k → walks of length k

64. How Week 10 and Week 11 connect

Week 10:
Can I reach this vertex?\text{Can I reach this vertex?}
Week 11:
What is the best path?\text{What is the best path?}
and:
Which vertices are reachable from which others?\text{Which vertices are reachable from which others?}
So the progression is:
traversal→reachability→weighted optimization\boxed{ \text{traversal} \rightarrow \text{reachability} \rightarrow \text{weighted optimization} }

65. What you should actually master

By the end of Week 11, you should be able to:
  1. Understand weighted graphs.
  2. Compute total path weight.
  3. Explain single-source shortest paths.
  4. Perform a relaxation step.
  5. Trace basic Dijkstra examples.
  6. Know why Dijkstra requires nonnegative weights.
  7. Trace basic Bellman–Ford logic.
  8. Understand why Bellman–Ford uses ∣V∣−1|V|-1 rounds.
  9. Recognize and explain negative-weight cycles.
  10. Distinguish negative edges from negative cycles.
  11. Choose between BFS, Dijkstra and Bellman–Ford.
  12. Understand longest-path reasoning in DAGs.
  13. Define reachability.
  14. Define transitive closure.
  15. Read/write adjacency matrices.
  16. Multiply small matrices.
  17. Understand: (Ak)ij(A^k)_{ij} as counting length-kk walks.
  18. Distinguish walks from simple paths.
  19. Understand path reconstruction with parents.
If those are comfortable, Week 11 is under control.

Quick Recall & Flashcards

Test your active recall before proceeding to practice problems. Format:
Question :: Answer.
  • Relaxation step for edge (u,v)(u, v) with weight w(u,v)w(u, v) :: If dist[u]+w(u,v)<dist[v]dist[u] + w(u, v) < dist[v]: dist[v]=dist[u]+w(u,v)dist[v] = dist[u] + w(u, v)
  • Dijkstra's algorithm requirement :: All edge weights must be nonnegative (w(u,v)≥0w(u, v) \ge 0)
  • Bellman–Ford algorithm number of relaxation rounds :: ∣V∣−1|V| - 1 rounds over all edges
  • How Bellman–Ford detects negative-weight cycles :: A negative cycle exists if an edge can still be relaxed in the ∣V∣|V|-th round
  • Adjacency matrix power (Ak)ij(A^k)_{ij} interpretation :: Number of walks of length exactly kk from vertex ii to vertex jj
  • Transitive closure definition :: Reachability matrix indicating if a path of any length exists from ii to jj
  • Algorithm for single-source shortest path in DAG with arbitrary weights :: Topological sort + single relaxation pass in O(∣V∣+∣E∣)O(|V| + |E|)

Practice & Self-Check

Attempt these diagnostic questions to verify your operational understanding.
1

Question 1

Which algorithm is suitable for finding single-source shortest paths in a directed graph that contains negative edge weights but no negative cycles?
MCQ
3 Unit Assessment
A. Dijkstra’s Algorithm
B. Bellman–Ford Algorithm
C. Standard unweighted BFS
D. Kruskal’s Algorithm
2

Question 2

Let AA be the adjacency matrix of an unweighted graph. The entry (A3)ij(A^3)_{ij} represents:
MCQ
3 Unit Assessment
A. The shortest distance between vertex ii and vertex jj
B. The number of walks of length exactly 3 from vertex ii to vertex jj
C. The weight of edge (i,j)(i, j) cubed
D. Whether ii and jj belong to the same component

Active Recall Session

Document outline

Keep your place and jump directly to a heading.

Table of contents

No note selected

Open a chapter to see its outline, backlinks, and sources here.