Skip to main content

7.1 Graph Representations: Adjacency Matrix, List & Incidence Matrix

πŸ“šModule 07 β€’ Graphs & Network TraversalsTopic 7.1⏱️14 min read
🎯High-Yield For:Semester Exams β€’ Technical Interviews β€’ Engineering Foundations

πŸ’‘ Core Intuition: The 3-Second Mental Model​

🍳 The Everyday Analogy:​

Picture an airline route directory. You can publish it as a giant 500Γ—500500 \times 500 wall grid (instant yes/no lookup for "Direct flight from Delhi to Tokyo?" by checking Row DEL, Col NRT, at the cost of printing 250,000 mostly blank squares), OR print each airport's own compact departure list (DEL -> [BOM, BLR, DXB, NRT]) saving 98% of the paper!

πŸ’» Bridging to Computer Science:​

Unlike treesβ€”which forbid cycles and restrict every non-root node to a single parentβ€”a Graph G=(V,E)G = (V, E) models arbitrary many-to-many connections across ∣V∣|V| vertices and ∣E∣|E| edges. Choosing between an Adjacency Matrix, an Adjacency List, or an Incidence Matrix determines whether graph algorithms run in O(V2)\mathcal{O}(V^2) dense time or O(V+E)\mathcal{O}(V + E) sparse time.


πŸ”— Graph Invariants & Degree Theorems​

A graph G=(V,E)G = (V, E) pairs a finite vertex set VV with an edge set EE:

  • Undirected Graph: Edges are unordered bidirectional pairs (u,v)≑(v,u)(u, v) \equiv (v, u). At most ∣V∣(∣Vβˆ£βˆ’1)2\frac{|V|(|V|-1)}{2} simple edges exist.
  • Directed Graph (Digraph): Edges are ordered unidirectional arrows (u,v)β€…β€ŠβŸΉβ€…β€Šuβ†’v(u, v) \implies u \to v. At most ∣V∣(∣Vβˆ£βˆ’1)|V|(|V|-1) simple directed edges exist.

The Handshaking Lemma (Degree Conservation)​

Every undirected edge e={u,v}e = \{u, v\} adds +1+1 to both endpoints' degrees, yielding Euler's foundational invariant:

βˆ‘v∈Vdeg⁑(v)=2∣E∣(Undirected)βˆ‘v∈Vdegβ‘βˆ’(v)=βˆ‘v∈Vdeg⁑+(v)=∣E∣(Directed)\sum_{v \in V} \deg(v) = 2|E| \quad \text{(Undirected)} \qquad \sum_{v \in V} \deg^-(v) = \sum_{v \in V} \deg^+(v) = |E| \quad \text{(Directed)}

A direct corollary: the count of vertices with odd degree in any undirected graph is always even.


πŸ—ΊοΈ Adjacency Matrix vs. Adjacency List vs. Incidence Matrix​

Three canonical memory layouts represent the same directed graph cleanly in RAM:

1. Adjacency Matrix & Walk-Counting Powers (M^k)​

Store a ∣Vβˆ£Γ—βˆ£V∣|V| \times |V| matrix MM where M[u][v]=1M[u][v] = 1 (or edge weight ww) if edge (u,v)∈E(u, v) \in E, else 00:

  • Instant Edge Check: Checking whether edge (u,v)(u, v) exists takes strictly O(1)\mathcal{O}(1) time (M[u][v]).
  • Adding a New Vertex: Reallocating an (V+1)Γ—(V+1)(V+1) \times (V+1) contiguous matrix requires copying all old entries β€…β€ŠβŸΉβ€…β€Š\implies O(V2)\mathcal{O}(V^2).
  • Matrix Power Theorem: Computing Boolean/integer matrix powers MkM^k reveals connectivity directly β€” entry Mk[u][v]M^k[u][v] gives the exact number of walks of length kk starting at uu and terminating at vv!

2. Adjacency List​

Store an array of ∣V∣|V| linked lists (or dynamic vectors), where Adj[u] contains only nodes directly adjacent from uu:

  • Memory Overhead: Directed lists store strictly ∣E∣|E| edge records (O(V+E)\mathcal{O}(V + E) space); undirected lists store each edge twice (O(V+2E)\mathcal{O}(V + 2E) total nodes).
  • Neighbor Iteration: Scanning all outgoing neighbors of uu takes exact O(deg⁑+(u))\mathcal{O}(\deg^+(u)) time instead of blind O(V)\mathcal{O}(V) row scans!

3. Incidence Matrix (V x E Dimensions)​

Row vv, Column ee records endpoint incidence for edge ee:

  • Undirected: I[v][e]=1I[v][e] = 1 at both endpoints (every column sums to 22, ignoring self-loops).
  • Directed: I[u][e]=+1I[u][e] = \mathbf{+1} if edge ee leaves vertex uu (outward tail), I[v][e]=βˆ’1I[v][e] = -1 if edge ee enters vertex vv (inward head), and 0 otherwise β€” so every edge column sums cleanly to 00!

Adjacency Matrix vs. Adjacency List Complexity Trade-Offs

Choosing the right topology representation by edge density |E| relative to |V|^2

Dense Standard

Adjacency Matrix (V x V Grid)

πŸ”²
Dominant Architecture / DomainDense Graphs (|E| ~ V^2) & Floyd-Warshall
  • β€’Memory Space: Always Theta(V^2), even with zero edges.
  • β€’Check Edge (u, v): Instant O(1) array lookup.
  • β€’Find All Neighbors of u: Slow O(V) full row scan.
  • β€’Add New Vertex: Costly O(V^2) full table resize.
"Ideal for small dense graphs, bitset optimization, and M^k path powers."
Sparse Standard

Adjacency List (V Dynamic Lists)

πŸ”—
Dominant Architecture / DomainReal-World Sparse Networks (Web, Social, Maps)
  • β€’Memory Space: Proportional Theta(V + E).
  • β€’Check Edge (u, v): Requires O(deg(u)) list search.
  • β€’Find All Neighbors of u: Exact optimal O(deg(u)).
  • β€’Add New Vertex: Amortized O(1) vector append.
"Real networks average deg(v) << V, cutting RAM & BFS/DFS from V^2 to V + E."

🎯 Vertex Eccentricity, Diameter & Graph Center​

In weighted or unweighted connected networks, shortest-path distances d(u,v)d(u, v) define central routing hubs:

  • Eccentricity Ο΅(v)\epsilon(v): The greatest shortest-path distance from vertex vv to any other vertex in the graph: Ο΅(v)=max⁑u∈Vd(v,u)\epsilon(v) = \max_{u \in V} d(v, u) (or maximum shortest distance incoming to a destination sink vertex vv).
  • Graph Diameter: max⁑v∈VΟ΅(v)\max_{v \in V} \epsilon(v) (worst-case hop/weight span across the whole graph).
  • Graph Radius: min⁑v∈VΟ΅(v)\min_{v \in V} \epsilon(v).
  • Graph Center: Any vertex cc whose eccentricity equals the Graph Radius β€” placing an ambulance station or cache proxy at the Center minimizes worst-case response time!

🏭 Real-World Production Context: Sparse CSR & Graph Systems​

Graph Memory Layouts Across Systems Engineering

Matching memory representation to graph sparsity drives orders-of-magnitude speedups

πŸ—ΊοΈ

GPS Road Routing Engines

CSR / Adjacency Lists
  • Road intersections average degree ~3 to 4 across 100M+ global vertices.
  • Compressed Sparse Row (CSR) packs adjacency lists into flat cache-friendly arrays.
🧠

Neural Network & Social Embedding Graphs

Adjacency Matrix / SpMM
  • Graph Neural Networks multiply Adjacency Matrix powers M^k directly on GPU tensor cores.
  • Dense sub-blocks use matrix layout for vectorized SIMD throughput.
⚑

Power Grid & Circuit KCL Solvers

Directed Incidence Matrix
  • Directed +1 / -1 Incidence Matrices encode Kirchhoff's Current Law cleanly (A * I = 0).
  • Solves voltage potentials and flow conservation via linear algebra directly.
🌐

CDN Anycast Hub Placement

Eccentricity & Center
  • Selects POP server centers minimizing max worst-case RTT (minimum eccentricity) across ISP links.
  • Reduces tail-latency bottlenecks across autonomous systems.

πŸ“ Numerical Applications & Worked Examples​

πŸ“Problem Statement: Memory Footprint, Incidence Matrix & Eccentricitytheorem
  1. A social network stores V=10,000V = 10{,}000 users where each user averages 5050 symmetric undirected friendships (∣E∣=250,000|E| = 250{,}000). Compare memory slots consumed by a 1-byte Adjacency Matrix vs. an Adjacency List (8-byte pointer + 4-byte integer vertex ID = 12 bytes per list node, plus 8-byte head pointer per vertex).
  2. In a directed incidence matrix IVΓ—EI_{V \times E} with 44 vertices and 44 directed edges (e1: A->B, e2: A->C, e3: B->D, e4: C->D), write the column vector for e2 and verify its column sum.

Step-by-Step Solution:​

  1. Adjacency Matrix vs. Adjacency List Memory:

    • Adjacency Matrix: V2Γ—1Β byte=10,000Γ—10,000=100Β MBV^2 \times 1\text{ byte} = 10{,}000 \times 10{,}000 = \mathbf{100\text{ MB}}!
    • Undirected Adjacency List: VV head pointers + 2∣E∣2|E| edge nodes: 10,000Γ—8+(2Γ—250,000)Γ—12=80,000+6,000,000=6.08Β MB10{,}000 \times 8 + (2 \times 250{,}000) \times 12 = 80{,}000 + 6{,}000{,}000 = \mathbf{6.08\text{ MB}} Switching to an Adjacency List saves >93% RAM even at V=104V = 10^4, and for V=106V = 10^6 an Adjacency Matrix would require 1Β Terabyte1\text{ Terabyte}!
  2. Directed Incidence Column for e2: A -> C: Ordering rows as (A, B, C, D):

    • Tail A gets +1+1 (outgoing source)
    • Head C gets βˆ’1-1 (incoming target)
    • Non-incident B, D get 0
    • Column vector: [+1, 0, -1, 0]^T, whose entries sum strictly to +1+0+(βˆ’1)+0=0+1 + 0 + (-1) + 0 = \mathbf{0}.

🎯 Exam & Interview Pitfall Check​

Core Conceptual Questions
  1. In an undirected graph with 12 vertices where every vertex has degree β‰₯3\ge 3, what is the minimum possible number of edges?
    • By Handshaking Lemma, 2∣E∣=βˆ‘deg⁑(v)β‰₯12Γ—3=36β€…β€ŠβŸΉβ€…β€Šβˆ£E∣β‰₯182|E| = \sum \deg(v) \ge 12 \times 3 = 36 \implies |E| \ge \mathbf{18}.
  2. What happens to row sums and column sums in a directed Adjacency Matrix MM?
    • Row uu sum = deg⁑+(u)\deg^+(u) (out-degree); Column vv sum = degβ‘βˆ’(v)\deg^-(v) (in-degree).
  3. Why is checking edge (u,v)(u, v) slower on an Adjacency List unless modified?
    • Scanning Adj[u] takes O(deg⁑+(u))\mathcal{O}(\deg^+(u)) β€” whereas sorting each list gives O(log⁑deg⁑+(u))\mathcal{O}(\log \deg^+(u)) or backing it with a hash set gives O(1)\mathcal{O}(1) expected time.
Common Interview Traps: Architectural Trade-Offs
  • Forgetting Undirected Edges Store 2 Nodes in Adjacency Lists: An undirected graph with EE edges occupies V+2EV + 2E nodes in memory (both Adj[u] contains v and Adj[v] contains u), NOT V+EV + E!
  • Diagonal Trace Confusion in Undirected Adjacency Matrices: Self-loops (u,u)(u, u) appear on the main diagonal M[u][u]=1M[u][u] = 1; under the standard definition of simple graph degree, a self-loop contributes +2+2 to vertex uu's undirected degree!
  • Assuming Incidence Matrix Outperforms Adjacency Matrix for Algorithm Design: Incidence matrices consume ∣Vβˆ£β‹…βˆ£E∣|V| \cdot |E| space (even larger than ∣V∣2|V|^2 whenever ∣E∣>∣V∣|E| > |V|!) and make neighbor enumeration O(∣E∣)\mathcal{O}(|E|) per node β€” reserve Incidence Matrices strictly for hypergraphs, linear programming, and electrical flow equations.

πŸš€ Navigation & Next Steps​

Now that graphs sit cleanly in memory, let's explore how to traverse them level-by-level in Topic 7.2 β€” Breadth-First Search: Shortest Paths & Odd-Cycle Detection.

πŸš€ Level Up Your Engineering Mindset

Never Study in Isolation. Join Binary Dose.

Connect with fellow engineers, clear conceptual doubts, and get 2 visual breakdowns & engineering mental models daily across our community channels.

Discord
Official Hub

Discord Community

Start at #welcome-and-rules, say hello in #general-chat, clear doubts, and collaborate with engineers worldwide.

Join Discord Server→
⚑
Daily Knowledge Drops

Daily Visual Deep-Dives

Bite-sized system design schematics, core OS internals, and DSA intuition served right into your feeds every single day.

πŸ’‘Help keep Binary Dose free for students, or share your articles and notes.