7.1 Graph Representations: Adjacency Matrix, List & Incidence Matrix
π‘ Core Intuition: The 3-Second Mental Modelβ
π³ The Everyday Analogy:β
Picture an airline route directory. You can publish it as a giant 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 models arbitrary many-to-many connections across vertices and edges. Choosing between an Adjacency Matrix, an Adjacency List, or an Incidence Matrix determines whether graph algorithms run in dense time or sparse time.
πTable of Contents
- π Graph Invariants & Degree Theorems
- πΊοΈ Adjacency Matrix vs. Adjacency List vs. Incidence Matrix
- π― Vertex Eccentricity, Diameter & Graph Center
- π Real-World Production Context: Sparse CSR & Graph Systems
- π Numerical Applications & Worked Examples
- π― Exam & Interview Pitfall Check
- π Navigation & Next Steps
π Graph Invariants & Degree Theoremsβ
A graph pairs a finite vertex set with an edge set :
- Undirected Graph: Edges are unordered bidirectional pairs . At most simple edges exist.
- Directed Graph (Digraph): Edges are ordered unidirectional arrows . At most simple directed edges exist.
The Handshaking Lemma (Degree Conservation)β
Every undirected edge adds to both endpoints' degrees, yielding Euler's foundational invariant:
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 matrix where (or edge weight ) if edge , else :
- Instant Edge Check: Checking whether edge exists takes strictly time (
M[u][v]). - Adding a New Vertex: Reallocating an contiguous matrix requires copying all old entries .
- Matrix Power Theorem: Computing Boolean/integer matrix powers reveals connectivity directly β entry gives the exact number of walks of length starting at and terminating at !
2. Adjacency Listβ
Store an array of linked lists (or dynamic vectors), where Adj[u] contains only nodes directly adjacent from :
- Memory Overhead: Directed lists store strictly edge records ( space); undirected lists store each edge twice ( total nodes).
- Neighbor Iteration: Scanning all outgoing neighbors of takes exact time instead of blind row scans!
3. Incidence Matrix (V x E Dimensions)β
Row , Column records endpoint incidence for edge :
- Undirected: at both endpoints (every column sums to , ignoring self-loops).
- Directed: if edge leaves vertex (outward tail), if edge enters vertex (inward head), and
0otherwise β so every edge column sums cleanly to !
Adjacency Matrix vs. Adjacency List Complexity Trade-Offs
Choosing the right topology representation by edge density |E| relative to |V|^2
Adjacency Matrix (V x V Grid)
- β’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.
Adjacency List (V Dynamic Lists)
- β’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.
π― Vertex Eccentricity, Diameter & Graph Centerβ
In weighted or unweighted connected networks, shortest-path distances define central routing hubs:
- Eccentricity : The greatest shortest-path distance from vertex to any other vertex in the graph: (or maximum shortest distance incoming to a destination sink vertex ).
- Graph Diameter: (worst-case hop/weight span across the whole graph).
- Graph Radius: .
- Graph Center: Any vertex 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β
- A social network stores users where each user averages symmetric undirected friendships (). 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).
- In a directed incidence matrix with vertices and directed edges (
e1: A->B, e2: A->C, e3: B->D, e4: C->D), write the column vector fore2and verify its column sum.
Step-by-Step Solution:β
-
Adjacency Matrix vs. Adjacency List Memory:
- Adjacency Matrix: !
- Undirected Adjacency List: head pointers + edge nodes: Switching to an Adjacency List saves >93% RAM even at , and for an Adjacency Matrix would require !
-
Directed Incidence Column for
e2: A -> C: Ordering rows as(A, B, C, D):- Tail
Agets (outgoing source) - Head
Cgets (incoming target) - Non-incident
B, Dget0 - Column vector:
[+1, 0, -1, 0]^T, whose entries sum strictly to .
- Tail
π― Exam & Interview Pitfall Checkβ
- In an undirected graph with 12 vertices where every vertex has degree , what is the minimum possible number of edges?
- By Handshaking Lemma, .
- What happens to row sums and column sums in a directed Adjacency Matrix ?
- Row sum = (out-degree); Column sum = (in-degree).
- Why is checking edge slower on an Adjacency List unless modified?
- Scanning
Adj[u]takes β whereas sorting each list gives or backing it with a hash set gives expected time.
- Scanning
- Forgetting Undirected Edges Store 2 Nodes in Adjacency Lists: An undirected graph with edges occupies nodes in memory (both
Adj[u]containsvandAdj[v]containsu), NOT ! - Diagonal Trace Confusion in Undirected Adjacency Matrices: Self-loops appear on the main diagonal ; under the standard definition of simple graph degree, a self-loop contributes to vertex 's undirected degree!
- Assuming Incidence Matrix Outperforms Adjacency Matrix for Algorithm Design: Incidence matrices consume space (even larger than whenever !) and make neighbor enumeration 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.
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 Community
Start at #welcome-and-rules, say hello in #general-chat, clear doubts, and collaborate with engineers worldwide.