Graph Representations — Adjacency Matrix vs Adjacency List — Complete Beginner Guide
Learning Objectives
- Build a graph with a matrix and a list
- Compute space cost for both layouts
- Compare neighbor iteration speed
- Support weights in each design
- Choose a representation from graph density
Two Storage Philosophies
Graph algorithms need neighbor access. Two standard layouts provide it.
| Layout | Idea |
|---|---|
| Adjacency matrix | Grid of cells where row meets column |
| Adjacency list | Map from vertex to neighbor collection |
Adjacency Matrix
A two-dimensional grid stores edge presence or weight. Cell row i and column j describes the edge from i to j.
For an undirected graph, the matrix is symmetric. For a directed graph, only one direction is set.
def build_matrix(n, edges, directed=False):
matrix = [[0] * n for _ in range(n)]
for a, b in edges:
matrix[a][b] = 1
if not directed:
matrix[b][a] = 1
return matrix
def has_edge(matrix, a, b):
return matrix[a][b] == 1
n = 4
edges = [(0, 1), (1, 2), (2, 3)]
graph = build_matrix(n, edges)
print(has_edge(graph, 0, 1)) # True
print(has_edge(graph, 0, 3)) # False
Matrix Complexity
| Task | Cost |
|---|---|
| Space | O of V squared |
| Check edge a to b | O(1) |
| List neighbors of v | O(V) |
| Add edge | O(1) |
| Remove edge | O(1) |
Matrices shine when the graph is dense or when you repeatedly test arbitrary pairs.
Adjacency List
Each vertex stores a list or set of neighbors. Sparse graphs waste almost nothing.
def build_list(n, edges, directed=False):
graph = [[] for _ in range(n)]
for a, b in edges:
graph[a].append(b)
if not directed:
graph[b].append(a)
return graph
def neighbors(graph, v):
return graph[v]
n = 4
edges = [(0, 1), (1, 2), (2, 3)]
graph = build_list(n, edges)
print(neighbors(graph, 1)) # 0 and 2
For weighted graphs, store pairs of neighbor and weight instead of bare ids.
# Weighted adjacency list entry style
# vertex 0 connects to vertex 1 with weight 4
weighted = {0: [(1, 4)], 1: [(0, 4)]}
List Complexity
| Task | Cost |
|---|---|
| Space | O of V plus E |
| Check edge a to b | O of degree of a, or O(1) with set |
| List neighbors of v | O of degree of v |
| Add edge | O(1) append |
| Remove edge | O of degree of a |
Side-by-Side Table
| Criteria | Matrix | List |
|---|---|---|
| Space dense graph | Efficient enough | Can hold duplicates overhead |
| Space sparse graph | Wastes V squared cells | Compact |
| Edge existence query | O(1) | O of degree unless set |
| Neighbor scan | Scans V slots | Scans real neighbors only |
| BFS or DFS total time | O of V squared | O of V plus E |
| Simple to code | Very | Very |
| Edge weights | Cell holds weight | Pair list holds weight |
Density Decision Rule
Let density equal E divided by the maximum possible edges.
| Density | Preferred Layout |
|---|---|
| High, near complete | Matrix |
| Low, typical networks | List |
| Mixed | List with optional set for fast queries |
| Tiny V under about one hundred | Either often fine |
Memory Math
For ten thousand vertices:
| Layout | Rough Cell Count |
|---|---|
| Matrix | One hundred million cells |
| List with ten edges each | One hundred thousand entries |
The matrix explodes while the list stays modest. For five hundred nearly complete vertices, the matrix is fine and scans stay simple.
Traversal Impact
BFS and DFS visit real edges once when using lists, giving O of V plus E total. Matrix neighbor loops always touch V columns per vertex even if most cells are empty, pushing total work toward V squared.
Representation Choice Drill
Walk a few size estimates before choosing a layout. One thousand vertices with average degree five means about five thousand directed entries, perfect for lists. Two hundred vertices fully connected means about forty thousand matrix cells, still fine and simpler for edge checks.
def space_estimate(v, e, dense_threshold=None):
matrix_cells = v * v
list_entries = 2 * e # undirected counted both ways
if dense_threshold is None:
dense_threshold = matrix_cells / 2
prefer_matrix = e >= dense_threshold
return matrix_cells, list_entries, prefer_matrix
print(space_estimate(100, 4000))
print(space_estimate(1000, 5000))
Add a second question to every design: do you need O(1) arbitrary edge existence checks? If yes and memory allows, a matrix or a set of encoded pairs helps. If you only walk neighbors during BFS or DFS, a list wins.
Finish by rewriting one matrix BFS into list BFS and comparing visited loops. Seeing V squared collapse into V plus E makes the theory concrete.
Key Takeaways
💡
- Adjacency matrices give O(1) edge checks and V squared space
- Adjacency lists give O of V plus E traversals and V plus E space
- Dense graphs favor matrices; sparse graphs favor lists
- Weighted graphs store weights in cells or neighbor pairs
- Most real-world social and map graphs stay sparse, so lists win
Practice Questions
- Compute matrix and list space for one million vertices with only two million edges.
- Why does scanning matrix neighbors hurt BFS even when few edges exist?
- Choose a representation for a road network of one hundred thousand intersections and justify.
Extended Learning: Beyond the Basics
Key Concepts Summary
This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.
Prerequisite Knowledge
Before studying this topic in depth, ensure you understand:
- Basic definitions and terminology
- Core formulas and their derivations
- Common applications in real-world scenarios
- Typical pitfalls and misconceptions
Step-by-Step Walkthrough
Let us work through a complete example to solidify understanding:
Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.
Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.
Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.
Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.
Common Mistakes to Avoid
- Misidentifying the problem type — Always start by categorizing the problem
- Incorrect formula application — Verify the formula applies to your specific case
- Unit errors — Always check units are consistent throughout
- Sign errors — Pay careful attention to positive and negative values
- Rounding too early — Keep full precision until the final answer
- Forgetting constraints — Check that solutions satisfy all given conditions
Real-World Applications
Understanding this concept is essential for:
- Advanced problem solving in examinations
- Building intuition for more complex topics
- Developing analytical thinking skills
- Applying mathematical reasoning to practical situations
Practice Exercises
- Basic: Solve 5 problems of increasing difficulty using the core concept.
- Intermediate: Apply the concept to word problems with multiple steps.
- Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
- Challenge: Create your own problem that requires this concept plus additional knowledge.
Interview and Exam Tips
- Common question patterns: Identify which exam or interview formats test this topic
- Time management: Practice completing problems within time constraints
- Common traps: Know the typical mistakes examiners set as distractors
- Verification strategy: Develop a quick method to check your answer
Related Topics
- Previous Topic — Build on the foundation laid here
- Next Topic — See how this concept extends to more advanced material
- Practice Problems — Additional exercises with solutions
- Video Explanation — Visual walkthrough of key concepts
Quick Reference Card
| Concept | Formula/Rule | Key Insight | Common Use |
|---|---|---|---|
| Core Definition | See main text | Understand the intuition | Foundation for all applications |
| Key Formula | See main text | Memorize the derivation | Direct problem solving |
| Special Case | See main text | Recognize when it applies | Simplifies complex problems |
| Edge Case | See main text | Know the limitations | Avoids errors |
Further Reading
For students who want to go deeper:
- Standard textbooks on the subject
- Research papers applying this concept
- Online courses with video explanations
- Practice problem collections with detailed solutions