2D Arrays (Matrices)
DSA · Arrays and Searching
Theory
A two-dimensional array stores data in rows and columns, like a spreadsheet or a chessboard. In Python it is usually a list of lists: grid[r][c] reads the value in row r and column c. Matrices appear everywhere in interviews: images are grids of pixels, game boards are grids of cells, and many dynamic programming tables are 2D. The key skills are iterating row by row, moving to neighbours (up, down, left, right) without leaving the grid, and transforming the whole matrix, for example transposing it or rotating it by 90 degrees. Memory is laid out row after row, so reading a matrix row-wise is faster than column-wise in most languages.
Why we use it
Many real problems are naturally two-dimensional: maps, seating charts, images, spreadsheets and DP tables. Knowing how to index and traverse a grid safely is the base for flood fill, path finding and matrix DP.
When to use it
Use a 2D array when data has two coordinates. Use a dictionary of (row, col) keys instead when the grid is huge but mostly empty (sparse).
How it works
- Start at row 0
- For each row r
- For each column c in that row
- Process grid[r][c]
- Need neighbours? Yes: Check (r±1,c),(r,c±1) inside bounds. No: Continue.
- All cells visited
Syntax
Create grid = [[0] * cols for _ in range(rows)]
Read grid[r][c] O(1)
Transpose list(zip(*grid)) O(r*c)
Neighbours (r±1, c), (r, c±1) with bounds checkExample
grid = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
]
rows, cols = len(grid), len(grid[0])
print("Middle cell:", grid[1][1])
print("Row sums:", [sum(row) for row in grid])
print("Column sums:", [sum(grid[r][c] for r in range(rows)) for c in range(cols)])
rotated = [list(row) for row in zip(*grid[::-1])] # 90 degrees clockwise
print("Rotated:", rotated)
def neighbours(r, c):
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
nr, nc = r + dr, c + dc
if 0 <= nr < rows and 0 <= nc < cols:
yield grid[nr][nc]
print("Neighbours of 5:", sorted(neighbours(1, 1)))
print("Neighbours of 1:", sorted(neighbours(0, 0)))Key points
- Never create a grid with [[0] * cols] * rows: every row would be the same list
- Always check bounds before moving to a neighbour
- Rotating clockwise = reverse the rows, then transpose
- Row-wise loops are usually faster than column-wise loops