Graph Construction
2D Array
Data Structures
Algorithm Design
Programming Techniques

How can I build a graph from a 2D array?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

The first step is to decide what the 2D array represents. In practice, "build a graph from a 2D array" usually means one of two things: either the array is already an adjacency matrix, or the array is a grid and each cell should become a node.

Case 1: The 2D Array Is an Adjacency Matrix

If matrix[i][j] tells you whether vertex i connects to vertex j, then the graph is already encoded. The usual task is just to convert it into a more convenient representation, such as an adjacency list.

python
1def adjacency_matrix_to_list(matrix):
2    graph = {}
3    for i, row in enumerate(matrix):
4        graph[i] = []
5        for j, edge in enumerate(row):
6            if edge:
7                graph[i].append(j)
8    return graph
9
10
11matrix = [
12    [0, 1, 0, 1],
13    [0, 0, 1, 0],
14    [0, 0, 0, 1],
15    [0, 0, 0, 0],
16]
17
18print(adjacency_matrix_to_list(matrix))

Output:

python
{0: [1, 3], 1: [2], 2: [3], 3: []}

If the matrix stores weights, use neighbor-weight pairs instead of plain neighbor IDs.

Case 2: The 2D Array Is a Grid Map

In pathfinding, games, and maze problems, a 2D array usually represents space. Each passable cell becomes a node, and edges connect neighboring cells.

For a four-direction grid, each cell can connect to:

  • up
  • down
  • left
  • right

You usually skip blocked cells such as walls.

python
1def build_grid_graph(grid):
2    rows = len(grid)
3    cols = len(grid[0])
4    graph = {}
5    directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
6
7    for r in range(rows):
8        for c in range(cols):
9            if grid[r][c] == 1:
10                continue
11
12            node = (r, c)
13            graph[node] = []
14
15            for dr, dc in directions:
16                nr = r + dr
17                nc = c + dc
18
19                if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == 0:
20                    graph[node].append((nr, nc))
21
22    return graph
23
24
25grid = [
26    [0, 0, 1],
27    [0, 0, 0],
28    [1, 0, 0],
29]
30
31graph = build_grid_graph(grid)
32print(graph[(1, 1)])

In this example, 0 means passable and 1 means blocked.

Which Representation Should You Keep

Adjacency lists are usually the best representation once the graph has been built. They are compact for sparse graphs and work well with BFS, DFS, Dijkstra, and A-star.

Adjacency matrices are useful when:

  • the graph is dense
  • edge existence checks must be constant time
  • the input already arrives as a square matrix

For grid graphs, adjacency lists are almost always the better choice because each node has only a small number of neighbors.

Directed and Weighted Variants

Your conversion logic depends on the semantics of the input:

  • for an undirected graph, both endpoints should see each other
  • for a directed graph, add only the allowed direction
  • for weighted edges, store pairs such as ((nr, nc), cost)

For example, a terrain map might assign different movement costs to mud, road, and water tiles. In that case, the graph nodes stay the same but the edges carry weights.

Common Pitfalls

The biggest mistake is not clarifying what the 2D array means. An adjacency matrix and a grid map require different graph-building logic.

Another mistake is forgetting bounds checks around the edges of the grid. Off-by-one errors are common when testing neighbors.

People also accidentally include blocked cells as nodes. If a cell is impassable, it usually should not appear in the graph at all.

Finally, for undirected graphs, make sure your representation is actually symmetric. Missing the reverse edge is a common source of traversal bugs.

Summary

  • A 2D array may represent either an adjacency matrix or a spatial grid.
  • Convert adjacency matrices by scanning rows for existing edges.
  • Convert grids by turning passable cells into nodes and linking valid neighbors.
  • Adjacency lists are the most useful output format for most sparse graphs.
  • Clarify direction, weights, and blocked cells before writing the conversion code.

Course illustration
Course illustration

All Rights Reserved.