Week 8: Graph Algorithms — Routes, Paths & Adjacency Matrices (Layered)
3371 words
17 min read
2026-09-12
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
Layered chapter on graph algorithms: adjacency matrices, matrix power walks, level-order BFS, Warshall reachability, and question-pattern anatomy. # Week 8: Graph Algorithms — Routes, Paths & Adjacency Matrices > **Acceptance Standard:** This chapter serves as a stand-alone textbook for any beginner studying IIT Mad...

Week 8: Graph Algorithms — Routes, Paths & Adjacency Matrices
Acceptance Standard: This chapter serves as a stand-alone textbook for any beginner studying IIT Madras BSCS1001. No video lecture or external slide deck is required to achieve complete conceptual mastery, trace every loop execution, and solve all eight recurring exam question patterns.
1. Orientation & Mental Model
The Real-World Scenario: The Railway Transit Grid
Imagine you are standing at Chennai Central railway station holding a railway map. You need to reach New Delhi.
(Chennai) ----[Train 101]----> (Bangalore) ----[Train 105]----> (Delhi) \ | ^ \ | [Train 102] / \ v / [Train 103] (Mumbai) -----[Train 104]-------/ \ ^ \ / +----------------------+
In transit engineering, you face three immediate questions:
- Direct Transit (0 Changes / 1 Hop): Is there a single train that leaves Chennai and terminates in Delhi without requiring you to switch trains?
- One Change (1 Stopover / 2 Hops): Can you reach Delhi by switching trains exactly once at an intermediate junction (e.g., Chennai → Bangalore → Delhi, or Chennai → Mumbai → Delhi)?
- Multi-Hop Reachability: If you have infinite time, can you reach Delhi at all through any valid sequence of trains?
In computer science and computational thinking, this physical railway network is a Directed Graph (Digraph):
- Vertices (Nodes): The stations (Chennai, Bangalore, Mumbai, Delhi).
- Directed Edges (Arcs): The train services flowing strictly from origin to destination.
- Paths / Walks: The sequences of edges traversed from start to finish.
The Computational Breakthrough: Algebraic Graph Theory
How does a computer answer "Can I get from A to B in 2 steps?" without drawing a physical diagram?
The core insight of Week 8 is that graph navigation is identical to matrix multiplication:
- Store direct connections in a square grid of 0s and 1s called the Adjacency Matrix A.
- To find all 2-step routes, you do not need recursive path searching; you simply compute the matrix product A×A=A2.
- The entry (Ak)[i][j] does not merely tell you if you can travel from station i to station j in k steps—it counts the exact number of distinct k-step routes available!
2. Terminology, Notation & Etymology
To prevent confusion in exam questions, memorize the precise distinction between these formal graph theory terms:
| Term | Symbol / Syntax | Origin / Etymology | Precise Definition |
|---|---|---|---|
| Vertex (plural: Vertices) | V, or {v0,v1,…} | Latin vertex ("highest point, turning point, summit"). | A fundamental discrete entity or node in the graph (e.g., a city or station). |
| Directed Edge (Arc) | e=(u,v) | Latin arcuare ("to bend like a bow"). | An ordered pair of vertices signifying a one-way connection from tail u to head v. |
| Adjacency Matrix | A∈{0,1}n×n | Latin adjacere ("to lie near or border upon"). | An n×n table where A[i][j]=1 if an edge exists from vertex i to vertex j, and 0 otherwise. |
| Walk | v0,e1,v1,…,vk | Old English wealcan ("to roll, turn, wander"). | An alternating sequence of vertices and edges where repeated vertices and repeated edges are permitted. |
| Path (Simple Path) | v0,v1,…,vk | Old French pat ("way, track"). | A walk in which no vertex is repeated (except possibly the start and end in a cycle). |
| Hop | k hops | Old English hoppian ("to leap or spring"). | An individual edge transition. A route with k hops traverses exactly k edges and visits k−1 intermediate stopovers. |
| In-Degree | deg−(v) | — | The number of directed edges entering vertex v. In an adjacency matrix, it is the sum of column v: ∑iA[i][v]. |
| Out-Degree | deg+(v) | — | The number of directed edges leaving vertex v. In an adjacency matrix, it is the sum of row v: ∑jA[v][j]. |
| Transitive Closure | T or A∗ | Latin transitivus ("passing over to another"). | The reachability matrix where T[i][j]=1 if there exists a path of any length (≥1) from i to j. |
Warning
IITM Exam Vocabulary Trap: "Hops" vs. "Stops"
- 1 Hop = 1 Edge = 0 Intermediate Stops (Direct journey: A→B).
- 2 Hops = 2 Edges = 1 Intermediate Stop / 1 Transfer (A→K→B).
- k Hops = k Edges = k−1 Transfers. When an exam question asks for routes "within one transfer", it means ≤2 hops (A∪A2).
3. Foundational Mechanics: Representing Graphs as Matrices
Let our train network have n=4 unique stations mapped to zero-based integer indices:
0: Chennai1: Bangalore2: Mumbai3: Delhi
The dataset of directed train schedules is:
- Train 101: Chennai → Bangalore (0→1)
- Train 102: Bangalore → Mumbai (1→2)
- Train 103: Chennai → Mumbai (0→2)
- Train 104: Mumbai → Delhi (2→3)
- Train 105: Bangalore → Delhi (1→3)
Step 1: Constructing the Direct Adjacency Matrix A
An adjacency matrix A for n vertices is an n×n 2D array initialized to all zeros:
To: 0 (Chn) 1 (Blr) 2 (Mum) 3 (Del) From: 0 (Chn) 0 1 1 0 1 (Blr) 0 0 1 1 2 (Mum) 0 0 0 1 3 (Del) 0 0 0 0
The Adjacency Matrix Construction Algorithm (Pseudocode)
pseudoProcedure BuildAdjacencyMatrix(trains, stationList) n = length(stationList) // Initialize an n x n matrix with zeros A = Create2DArray(n, n, 0) // Populate indices map: stationName -> index stnIndex = Dictionary() for i from 0 to n - 1 do stnIndex[stationList[i]] = i end for // Insert direct directed edges for each train in trains do u = stnIndex[train.start] v = stnIndex[train.end] A[u][v] = 1 end for return A End Procedure
4. Algorithmic Depth & Trace: From Direct Edges to Multi-Hop Paths
Layer 1: The One-Hop (2-Edge) Transfer Algorithm
To travel from station i to station j with exactly one intermediate change at station k, two conditions must both be true:
- There must be a direct train from i to k:
A[i][k] == 1 - There must be a direct train from k to j:
A[k][j] == 1
If any station k∈{0,1,…,n−1} satisfies both conditions, then i can reach j in 2 hops!
pseudoProcedure ComputeTwoHopRoutes(A, n) // Initialize 2-hop matrix TwoHop = Create2DArray(n, n, 0) for i from 0 to n - 1 do // Origin station for j from 0 to n - 1 do // Destination station for k from 0 to n - 1 do // Candidate transfer junction if A[i][k] == 1 and A[k][j] == 1 then TwoHop[i][j] = 1 // Route confirmed through junction k end if end for end for end for return TwoHop End Procedure
Layer 2: The Algebraic Derivation of Matrix Powers
Observe the inner condition of the 3-nested loops:
Path exists via k⟺A[i][k]×A[k][j]=1
If we sum this product across all possible intermediate stations k∈{0,1,…,n−1}:
M2[i][j]=∑k=0n−1A[i][k]×A[k][j]
This is the mathematical definition of standard Matrix Multiplication:
M2=A×A=A2
The Fundamental Theorem of Graph Powers
Let A be the adjacency matrix of a directed graph. In the k-th matrix power Ak:
The entry (Ak)[i][j] is the exact number of distinct directed walks of length k from vertex i to vertex j.
Let us compute A2 manually for our railway network:
A=0000100011000110
Calculating row 0 (Chennai):
- (A2)[0][0]=(0⋅0)+(1⋅0)+(1⋅0)+(0⋅0)=0
- (A2)[0][1]=(0⋅1)+(1⋅0)+(1⋅0)+(0⋅0)=0
- (A2)[0][2]=(0⋅1)+(1⋅1)+(1⋅0)+(0⋅0)=1 (via Bangalore: Chennai → Bangalore → Mumbai)
- (A2)[0][3]=(0⋅0)+(1⋅1)+(1⋅1)+(0⋅0)=2 (Two distinct paths: Chennai → Bangalore → Delhi AND Chennai → Mumbai → Delhi)
Calculating row 1 (Bangalore):
- (A2)[1][3]=(0⋅0)+(0⋅1)+(1⋅1)+(1⋅0)=1 (via Mumbai: Bangalore → Mumbai → Delhi)
All other entries of row 1, 2, and 3 compute to 0.
A2=0000000010002100
Notice the value 2 at (A2)[0][3]! It tells the system that there are two independent 2-hop routes from Chennai to Delhi.
Layer 3: Computing 3-Hop Paths (A3)
What about journeys requiring 3 hops (2 intermediate train changes)?
A3=A2×A=0000000010002100×0000100011000110=0000000000001000
There is exactly one 3-hop route from Chennai (0) to Delhi (3):
Chennai (0)⟶Bangalore (1)⟶Mumbai (2)⟶Delhi (3)
Any path with length >3 produces the zero matrix Ak=0 for k≥4, because a simple path in a 4-vertex graph without cycles cannot have more than 3 edges.
5. Failure Modes & Common Exam Pitfalls
Common Student Misconception: "If A^2[i][j] > 0, then the shortest path from i to j is 2." | +---> WRONG! A direct edge A[i][j] = 1 might also exist! Shortest path is min { k : A^k[i][j] > 0 }.
Pitfall 1: Confusing Reachability (T) with Route Count (Ak)
- Matrix power Ak: An arithmetic integer matrix where entries represent the number of walks.
- Boolean Reachability Rk: A binary matrix where Rk[i][j]=1 if (Ak)[i][j]≥1, else 0.
- Transitive Closure T: The cumulative logical OR across all possible path lengths: T=A∨A2∨A3∨⋯∨An−1
Pitfall 2: The Two-Way Edge / Bounce-Back Walk Trap
If an undirected edge exists between u and v (meaning two directed edges u→v and v→u):
(A2)[u][u]≥1
Because u→v→u is a valid walk of length 2!
Students often incorrectly assume (A2)[u][u] must always be zero because you don't take a train to go back to your origin. In graph algebra, walks allow vertex repetition.
Pitfall 3: Off-By-One Transfer Counting
- Problem statement: "Find all pairs of stations reachable with at most 2 train changes."
- Correct computation: 2 changes = 3 hops. The answer is the logical OR of A∨A2∨A3.
- Common blunder: Computing only A2 (which corresponds to 1 change / 2 hops).
6. Question-Pattern Anatomy (8 Finite Exam Shapes)
Every question on graph routes and matrices in IITM CT fits one of these eight shapes:
Shape 1: Direct Verification of Adjacency
- Cue: "Given the edge list, find the entry A[i][j] or total number of non-zero entries."
- Attack Sequence:
- Count total directed edges m. The number of 1s in A is exactly m.
- For A[i][j], verify if directed edge i→j exists.
- Planted Trap: Mistaking an undirected edge for 1 entry instead of 2 symmetric entries A[i][j]=A[j][i]=1.
Shape 2: In-Degree and Out-Degree from Matrix Rows/Cols
- Cue: "Which station has no outgoing trains? / Which vertex is a sink?"
- Attack Sequence:
- Out-degree(i)=Row sum of row i. If ∑jA[i][j]=0, vertex i is a sink.
- In-degree(j)=Column sum of col j. If ∑iA[i][j]=0, vertex j is a source.
- Planted Trap: Summing the column when asked for out-degree. Row = Outgoing, Column = Incoming.
Shape 3: Number of Paths of Length 2 Between Two Nodes
- Cue: "How many 2-hop paths exist from vertex u to vertex v?"
- Attack Sequence: Compute the dot product of row u and column v: (A2)[u][v]=∑k=0n−1A[u][k]⋅A[k][v] Count how many indices k satisfy A[u][k]==1 AND A[k][v]==1.
- Planted Trap: Counting junctions where an edge exists to k, but no edge exists from k to v.
Shape 4: Shortest Route Identification
- Cue: "What is the minimum number of hops required to travel from u to v?"
- Attack Sequence:
- Check if A[u][v]==1 → 1 hop.
- Check if (A2)[u][v]>0 → 2 hops.
- Check if (A3)[u][v]>0 → 3 hops.
- Planted Trap: Choosing an answer based on geographic distance instead of topological edge count.
Shape 5: Detecting Cycles via Diagonal Entries
- Cue: "Does the graph contain a directed triangle (cycle of length 3)?"
- Attack Sequence: Compute the diagonal of A3: Cycle of length 3 through vertex i⟺(A3)[i][i]>0 The total number of directed triangles in the graph is 31∑i=0n−1(A3)[i][i].
- Planted Trap: Forgetting to divide by 3 when counting undirected triangles.
Shape 6: Reachability Within K Steps
- Cue: "Find the reachability matrix for all journeys with at most 2 hops."
- Attack Sequence: Compute R≤2=A∨A2 (or I∨A∨A2 if zero-hop self-reachability is included).
- Planted Trap: Computing A×A2=A3 instead of matrix addition/boolean OR.
Shape 7: Loop Termination in Reachability Exploration
- Cue: "In an n-vertex graph, what is the maximum power of A needed to check all simple paths?"
- Attack Sequence: A simple path in an n-vertex graph visits each vertex at most once, meaning it has at most n−1 edges. Therefore, the search stops at An−1.
- Planted Trap: Answering n or n2 instead of n−1.
Shape 8: Pseudocode Tracing of 3-Nested Matrix Loops
- Cue: "What is the final value of count in the given 3-nested loop?"
- Attack Sequence: Identify if the inner loop computes matrix multiplication (A×B) or transitive closure (Warshall-like update). Trace the outer loop index order: (i,j,k) vs (k,i,j).
- Planted Trap: Swapping the roles of k as intermediate junction with j as destination.
7. Interactive Verification & Attempt-First Self-Checks
1
Question 1
Type: MCQ | Marks: 1 | Topic: Matrix power walks
Consider a directed graph with 4 vertices {0,1,2,3} having the following adjacency matrix:
A=0000100001001010
How many distinct directed walks of length 2 exist from vertex 0 to vertex 3?
MCQ
Matrix power walks
3 Unit Assessment
A
0
B
1
C
2
D
3
2
Question 2
Type: MCQ | Marks: 1 | Topic: Adjacency matrix diagonal and vertex degree
A social network graph of 5 people has adjacency matrix A. An analyst computes the diagonal of A2:
diag(A2)=[(A2)[0][0],(A2)[1][1],(A2)[2][2],(A2)[3][3],(A2)[4][4]]
Assuming the graph is undirected with no self-loops (A[i][i]=0 and A[i][j]=A[j][i]), what does the diagonal entry (A2)[i][i] represent?
MCQ
Adjacency matrix diagonal and vertex degree
3 Unit Assessment
A
The number of triangles containing vertex i
B
The degree of vertex i (number of direct friends of i)
C
Always 0, because no self-loops exist in the network
D
The total number of people in the network reachable from i
3
Question 3
Type: MCQ | Marks: 1 | Topic: Level-order traversal & shortest hop distance
Consider the pseudocode below executed on an n×n adjacency matrix A:
pseudoProcedure PathCheck(A, n, startNode, endNode) visited = CreateArray(n, False) frontier = [startNode] visited[startNode] = True hops = 0 while length(frontier) > 0 do nextFrontier = [] for each u in frontier do if u == endNode then return hops end if for v from 0 to n - 1 do if A[u][v] == 1 and not visited[v] then visited[v] = True Append(nextFrontier, v) end if end for end for frontier = nextFrontier hops = hops + 1 end while return -1 End Procedure
What algorithmic paradigm does this procedure implement, and what does it return when
endNode is reachable?MCQ
Level-order traversal & shortest hop distance
3 Unit Assessment
A
Depth-First Search (DFS); returns the total number of paths
B
Breadth-First Search (BFS); returns the minimum number of hops (shortest path length)
C
Dijkstra's Algorithm; returns the minimum edge weights
D
Warshall's Algorithm; returns the boolean transitive closure
8. Next Action & Spacing Rail
- Next Invariant Chapter: Proceed to
Week 9: Recursion & Call Stacks (Layered)to master how recursive stack frames traverse branched decision trees. - Direct Application in Week 9 DFS: Notice how
PathCheckuses an iterative level frontier (BFS). In Week 9, we convert this into a recursive call stack to perform Depth-First Search (DFS). - Cross-Course Connection: In Mathematics I (
BSMA1001), see how eigenvalues of adjacency matrix A define graph connectivity and spectral clustering.
Chapter provenance: authored 2026-09-12 to the layered-chapter standard (
docs/roadmaps/2026-09-12-claude-content-ecosystem.md, syntax per docs/authoring/AUTHORING_COOKBOOK.md), scoped against the BSCS1001 syllabus vault and the imported 817 - Week 8- Graph Algorithms — Routes & Paths.md (untouched; this file is its new sibling).