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

  1. Start at row 0
  2. For each row r
  3. For each column c in that row
  4. Process grid[r][c]
  5. Need neighbours? Yes: Check (r±1,c),(r,c±1) inside bounds. No: Continue.
  6. 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 check

Example

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

DSA topics

Introduction to DSA

Arrays and Searching

Sorting Algorithms

Linked Lists

Stacks and Queues

Hashing

Trees

Heaps

Graphs

Algorithm Techniques

Classic Algorithms

Dynamic Programming

T
Tech Town
Log InSign Up Free
Home SQL Python DSA Power BI Snowflake Databricks Spark Gen AI Practice Problems Contest Blog

Data Structures & Algorithms

The complete DSA roadmap: theory, why and when to use every structure and algorithm, Big O complexity, and Python code you can run right here in the browser.

{{ sectionCount }}
Sections
{{ topicCount }}
Topics
Free
Forever
Hands-on practice Practice DSA Online 251 problems across 13 patterns, with hidden tests and step-by-step optimal solutions. Start practising →
Section {{ sec.num }}

{{ sec.label }}

DSA  /  {{ current.sectionLabel }}  /  {{ current.name }}

{{ current.name }}

Theory

{{ current.def }}

Why we use it

{{ current.why }}

When to use it

{{ current.when }}

Flowchart — how {{ current.name }} works
{{ nd.text }}
{{ nd.text }}
◇ {{ nd.text }}
Yes → {{ nd.yes }}
No → {{ nd.no }}
Step-by-step visualisation
{{ cell.v }}
{{ cell.i }} {{ cell.tag }}
Step {{ vizStepLabel }}: {{ vizNote }}
■ comparing ■ swapping / moving ■ done / found ■ out of range
Complexity & Pseudocode
{{ current.syntax }}
Example Code
{{ current.example }}
▶ Try It Live — runs real Python 3 in your browser (first run loads the engine)
{{ liveOutput }}
{{ liveError }}
Key Points — click to check off as you learn
  • {{ pt.mark }} {{ pt.text }}

Share this topic