Week 8: Graph Algorithms — Routes, Paths & Adjacency Matrices (Layered)

3371 words
17 min read
2026-09-12
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

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:
  1. Direct Transit (0 Changes / 1 Hop): Is there a single train that leaves Chennai and terminates in Delhi without requiring you to switch trains?
  2. One Change (1 Stopover / 2 Hops): Can you reach Delhi by switching trains exactly once at an intermediate junction (e.g., Chennai →\to Bangalore →\to Delhi, or Chennai →\to Mumbai →\to Delhi)?
  3. 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 AA.
  • To find all 2-step routes, you do not need recursive path searching; you simply compute the matrix product A×A=A2A \times A = A^2.
  • The entry (Ak)[i][j](A^k)[i][j] does not merely tell you if you can travel from station ii to station jj in kk steps—it counts the exact number of distinct kk-step routes available!

2. Terminology, Notation & Etymology

To prevent confusion in exam questions, memorize the precise distinction between these formal graph theory terms:
TermSymbol / SyntaxOrigin / EtymologyPrecise Definition
Vertex (plural: Vertices)VV, or {v0,v1,… }\{v_0, v_1, \dots\}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)e = (u, v)Latin arcuare ("to bend like a bow").An ordered pair of vertices signifying a one-way connection from tail uu to head vv.
Adjacency MatrixA∈{0,1}n×nA \in \{0, 1\}^{n \times n}Latin adjacere ("to lie near or border upon").An n×nn \times n table where A[i][j]=1A[i][j] = 1 if an edge exists from vertex ii to vertex jj, and 00 otherwise.
Walkv0,e1,v1,…,vkv_0, e_1, v_1, \dots, v_kOld 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,…,vkv_0, v_1, \dots, v_kOld French pat ("way, track").A walk in which no vertex is repeated (except possibly the start and end in a cycle).
Hopk hopsk \text{ hops}Old English hoppian ("to leap or spring").An individual edge transition. A route with kk hops traverses exactly kk edges and visits k−1k-1 intermediate stopovers.
In-Degreedeg−(v)\text{deg}^-(v)—The number of directed edges entering vertex vv. In an adjacency matrix, it is the sum of column vv: ∑iA[i][v]\sum_{i} A[i][v].
Out-Degreedeg+(v)\text{deg}^+(v)—The number of directed edges leaving vertex vv. In an adjacency matrix, it is the sum of row vv: ∑jA[v][j]\sum_{j} A[v][j].
Transitive ClosureTT or A∗A^*Latin transitivus ("passing over to another").The reachability matrix where T[i][j]=1T[i][j] = 1 if there exists a path of any length (≥1\ge 1) from ii to jj.
Warning
IITM Exam Vocabulary Trap: "Hops" vs. "Stops"
  • 1 Hop = 1 Edge = 0 Intermediate Stops (Direct journey: A→BA \to B).
  • 2 Hops = 2 Edges = 1 Intermediate Stop / 1 Transfer (A→K→BA \to K \to B).
  • kk Hops = kk Edges = k−1k-1 Transfers. When an exam question asks for routes "within one transfer", it means ≤2\le 2 hops (A∪A2A \cup A^2).

3. Foundational Mechanics: Representing Graphs as Matrices

Let our train network have n=4n = 4 unique stations mapped to zero-based integer indices:
  • 0: Chennai
  • 1: Bangalore
  • 2: Mumbai
  • 3: Delhi
The dataset of directed train schedules is:
  1. Train 101: Chennai →\to Bangalore (0→10 \to 1)
  2. Train 102: Bangalore →\to Mumbai (1→21 \to 2)
  3. Train 103: Chennai →\to Mumbai (0→20 \to 2)
  4. Train 104: Mumbai →\to Delhi (2→32 \to 3)
  5. Train 105: Bangalore →\to Delhi (1→31 \to 3)

Step 1: Constructing the Direct Adjacency Matrix AA

An adjacency matrix AA for nn vertices is an n×nn \times 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)

pseudo
Procedure 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 ii to station jj with exactly one intermediate change at station kk, two conditions must both be true:
  1. There must be a direct train from ii to kk: A[i][k] == 1
  2. There must be a direct train from kk to jj: A[k][j] == 1
If any station k∈{0,1,…,n−1}k \in \{0, 1, \dots, n-1\} satisfies both conditions, then ii can reach jj in 2 hops!
pseudo
Procedure 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\text{Path exists via } k \iff A[i][k] \times A[k][j] = 1
If we sum this product across all possible intermediate stations k∈{0,1,…,n−1}k \in \{0, 1, \dots, n-1\}: M2[i][j]=∑k=0n−1A[i][k]×A[k][j]M_2[i][j] = \sum_{k=0}^{n-1} A[i][k] \times A[k][j]
This is the mathematical definition of standard Matrix Multiplication: M2=A×A=A2M_2 = A \times A = A^2

The Fundamental Theorem of Graph Powers

Let AA be the adjacency matrix of a directed graph. In the kk-th matrix power AkA^k: The entry (Ak)[i][j](A^k)[i][j] is the exact number of distinct directed walks of length kk from vertex ii to vertex jj.
Let us compute A2A^2 manually for our railway network:
A=(0110001100010000)A = \begin{pmatrix} 0 & 1 & 1 & 0 \\ 0 & 0 & 1 & 1 \\ 0 & 0 & 0 & 1 \\ 0 & 0 & 0 & 0 \end{pmatrix}
Calculating row 0 (Chennai):
  • (A2)[0][0]=(0⋅0)+(1⋅0)+(1⋅0)+(0⋅0)=0(A^2)[0][0] = (0\cdot 0) + (1\cdot 0) + (1\cdot 0) + (0\cdot 0) = 0
  • (A2)[0][1]=(0⋅1)+(1⋅0)+(1⋅0)+(0⋅0)=0(A^2)[0][1] = (0\cdot 1) + (1\cdot 0) + (1\cdot 0) + (0\cdot 0) = 0
  • (A2)[0][2]=(0⋅1)+(1⋅1)+(1⋅0)+(0⋅0)=1(A^2)[0][2] = (0\cdot 1) + (1\cdot 1) + (1\cdot 0) + (0\cdot 0) = 1 (via Bangalore: Chennai →\to Bangalore →\to Mumbai)
  • (A2)[0][3]=(0⋅0)+(1⋅1)+(1⋅1)+(0⋅0)=2(A^2)[0][3] = (0\cdot 0) + (1\cdot 1) + (1\cdot 1) + (0\cdot 0) = 2 (Two distinct paths: Chennai →\to Bangalore →\to Delhi AND Chennai →\to Mumbai →\to Delhi)
Calculating row 1 (Bangalore):
  • (A2)[1][3]=(0⋅0)+(0⋅1)+(1⋅1)+(1⋅0)=1(A^2)[1][3] = (0\cdot 0) + (0\cdot 1) + (1\cdot 1) + (1\cdot 0) = 1 (via Mumbai: Bangalore →\to Mumbai →\to Delhi)
All other entries of row 1, 2, and 3 compute to 0.
A2=(0012000100000000)A^2 = \begin{pmatrix} 0 & 0 & 1 & 2 \\ 0 & 0 & 0 & 1 \\ 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 \end{pmatrix}
Notice the value 2 at (A2)[0][3](A^2)[0][3]! It tells the system that there are two independent 2-hop routes from Chennai to Delhi.

Layer 3: Computing 3-Hop Paths (A3A^3)

What about journeys requiring 3 hops (2 intermediate train changes)? A3=A2×A=(0012000100000000)×(0110001100010000)=(0001000000000000)A^3 = A^2 \times A = \begin{pmatrix} 0 & 0 & 1 & 2 \\ 0 & 0 & 0 & 1 \\ 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 \end{pmatrix} \times \begin{pmatrix} 0 & 1 & 1 & 0 \\ 0 & 0 & 1 & 1 \\ 0 & 0 & 0 & 1 \\ 0 & 0 & 0 & 0 \end{pmatrix} = \begin{pmatrix} 0 & 0 & 0 & 1 \\ 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 \end{pmatrix}
There is exactly one 3-hop route from Chennai (0) to Delhi (3): Chennai (0)⟶Bangalore (1)⟶Mumbai (2)⟶Delhi (3)\text{Chennai (0)} \longrightarrow \text{Bangalore (1)} \longrightarrow \text{Mumbai (2)} \longrightarrow \text{Delhi (3)}
Any path with length >3> 3 produces the zero matrix Ak=0A^k = 0 for k≥4k \ge 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 (TT) with Route Count (AkA^k)

  • Matrix power AkA^k: An arithmetic integer matrix where entries represent the number of walks.
  • Boolean Reachability RkR_k: A binary matrix where Rk[i][j]=1R_k[i][j] = 1 if (Ak)[i][j]≥1(A^k)[i][j] \ge 1, else 00.
  • Transitive Closure TT: The cumulative logical OR across all possible path lengths: T=A∨A2∨A3∨⋯∨An−1T = A \lor A^2 \lor A^3 \lor \dots \lor A^{n-1}

Pitfall 2: The Two-Way Edge / Bounce-Back Walk Trap

If an undirected edge exists between uu and vv (meaning two directed edges u→vu \to v and v→uv \to u): (A2)[u][u]≥1(A^2)[u][u] \ge 1 Because u→v→uu \to v \to u is a valid walk of length 2! Students often incorrectly assume (A2)[u][u](A^2)[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∨A3A \lor A^2 \lor A^3.
  • Common blunder: Computing only A2A^2 (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]A[i][j] or total number of non-zero entries."
  • Attack Sequence:
    1. Count total directed edges mm. The number of 1s in AA is exactly mm.
    2. For A[i][j]A[i][j], verify if directed edge i→ji \to j exists.
  • Planted Trap: Mistaking an undirected edge for 1 entry instead of 2 symmetric entries A[i][j]=A[j][i]=1A[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\text{Out-degree}(i) = \text{Row sum of row } i. If ∑jA[i][j]=0\sum_j A[i][j] = 0, vertex ii is a sink.
    • In-degree(j)=Column sum of col j\text{In-degree}(j) = \text{Column sum of col } j. If ∑iA[i][j]=0\sum_i A[i][j] = 0, vertex jj 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 uu to vertex vv?"
  • Attack Sequence: Compute the dot product of row uu and column vv: (A2)[u][v]=∑k=0n−1A[u][k]⋅A[k][v](A^2)[u][v] = \sum_{k=0}^{n-1} A[u][k] \cdot A[k][v] Count how many indices kk satisfy A[u][k]==1A[u][k] == 1 AND A[k][v]==1A[k][v] == 1.
  • Planted Trap: Counting junctions where an edge exists to kk, but no edge exists from kk to vv.

Shape 4: Shortest Route Identification

  • Cue: "What is the minimum number of hops required to travel from uu to vv?"
  • Attack Sequence:
    1. Check if A[u][v]==1A[u][v] == 1 →\to 1 hop.
    2. Check if (A2)[u][v]>0(A^2)[u][v] > 0 →\to 2 hops.
    3. Check if (A3)[u][v]>0(A^3)[u][v] > 0 →\to 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 A3A^3: Cycle of length 3 through vertex i  ⟺  (A3)[i][i]>0\text{Cycle of length 3 through vertex } i \iff (A^3)[i][i] > 0 The total number of directed triangles in the graph is 13∑i=0n−1(A3)[i][i]\frac{1}{3} \sum_{i=0}^{n-1} (A^3)[i][i].
  • Planted Trap: Forgetting to divide by 3 when counting undirected triangles.

Shape 6: Reachability Within KK Steps

  • Cue: "Find the reachability matrix for all journeys with at most 2 hops."
  • Attack Sequence: Compute R≤2=A∨A2R_{\le 2} = A \lor A^2 (or I∨A∨A2I \lor A \lor A^2 if zero-hop self-reachability is included).
  • Planted Trap: Computing A×A2=A3A \times A^2 = A^3 instead of matrix addition/boolean OR.

Shape 7: Loop Termination in Reachability Exploration

  • Cue: "In an nn-vertex graph, what is the maximum power of AA needed to check all simple paths?"
  • Attack Sequence: A simple path in an nn-vertex graph visits each vertex at most once, meaning it has at most n−1n-1 edges. Therefore, the search stops at An−1A^{n-1}.
  • Planted Trap: Answering nn or n2n^2 instead of n−1n-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×BA \times B) or transitive closure (Warshall-like update). Trace the outer loop index order: (i,j,k)(i, j, k) vs (k,i,j)(k, i, j).
  • Planted Trap: Swapping the roles of kk as intermediate junction with jj 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}\{0, 1, 2, 3\} having the following adjacency matrix: A=(0101001000010000)A = \begin{pmatrix} 0 & 1 & 0 & 1 \\ 0 & 0 & 1 & 0 \\ 0 & 0 & 0 & 1 \\ 0 & 0 & 0 & 0 \end{pmatrix}
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 AA. An analyst computes the diagonal of A2A^2: diag(A2)=[(A2)[0][0],(A2)[1][1],(A2)[2][2],(A2)[3][3],(A2)[4][4]]\text{diag}(A^2) = [(A^2)[0][0], (A^2)[1][1], (A^2)[2][2], (A^2)[3][3], (A^2)[4][4]] Assuming the graph is undirected with no self-loops (A[i][i]=0A[i][i] = 0 and A[i][j]=A[j][i]A[i][j] = A[j][i]), what does the diagonal entry (A2)[i][i](A^2)[i][i] represent?
MCQ
Adjacency matrix diagonal and vertex degree
3 Unit Assessment
A
The number of triangles containing vertex ii
B
The degree of vertex ii (number of direct friends of ii)
C
Always 0, because no self-loops exist in the network
D
The total number of people in the network reachable from ii

3

Question 3

Type: MCQ | Marks: 1 | Topic: Level-order traversal & shortest hop distance
Consider the pseudocode below executed on an n×nn \times n adjacency matrix AA:
pseudo
Procedure 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 PathCheck uses 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 AA 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).
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.