Graph Representation - aloalgo.com

Graph Representation

Before you can traverse or search a graph, you need to represent it in code. There are two main approaches: adjacency list and adjacency matrix.

Adjacency List

Each vertex stores a list of its neighbors. This is the most common representation and is space-efficient for sparse graphs.

Building from Edge List

Weighted Graph

Adjacency Matrix

A 2D array where matrix[i][j] indicates if an edge exists between vertices i and j. Good for dense graphs or when you need O(1) edge lookups.

Weighted Matrix

Comparison

OperationAdjacency ListAdjacency Matrix
SpaceO(V + E)O(V²)
Check edge existsO(degree)O(1)
Find all neighborsO(degree)O(V)
Add edgeO(1)O(1)
Best forSparse graphsDense graphs

Grid as a Graph

2D grids are implicit graphs. Each cell is a vertex, and adjacent cells are neighbors.

When to Use Which

  • Adjacency List: Most interview problems, sparse graphs, when you need to iterate over neighbors
  • Adjacency Matrix: Dense graphs, when you need O(1) edge lookups, Floyd-Warshall algorithm
  • Grid: Maze problems, flood fill, island counting
Was this helpful?
© 2026 aloalgo.com. All rights reserved.