Arrays — Visual Learning

2D Array Traversal —
Row, column, diagonal, spiral.

A 2D array (matrix) is the foundation of grid problems, image processing, and graph representation. Knowing how to traverse one — row by row, column by column, diagonally, or in a spiral — unlocks an entire class of interview problems. Watch the indices update cell by cell on LearnBug and every traversal pattern becomes instinctive.

O(n·m)Time complexity
4Traversal patterns
PythonLanguage

What is a 2D Array?

A 2D array is an array of arrays — a grid with rows and columns. Element at row i, column j is accessed as matrix[i][j]. An n×m matrix has n rows and m columns, holding n×m elements total. They appear everywhere: game boards, images (pixels), adjacency matrices for graphs, and dynamic programming tables.

Why visualization changes everything

It's hard to picture which cell matrix[i][j] refers to when you can only see indices in code. On LearnBug, the cell lights up on the actual grid as i and j increment — you see exactly which direction the traversal moves, where it wraps to the next row, and how diagonal or spiral patterns unfold cell by cell.

YouTube — 2D Array Traversal Explained
📺 Drop your YouTube embed here
LearnBug — grid cells lighting up in traversal order
🖼 Add a LearnBug screenshot here
4 Patterns

The four traversal patterns you need

Row-by-Row

Outer loop over rows (i), inner loop over columns (j). Visits every cell left to right, top to bottom. The default traversal pattern — used in matrix search, row sum, and printing.

O(n·m)Most common

Column-by-Column

Outer loop over columns, inner loop over rows. Swap the loop order. Used in transpose operations, column sums, and cache-aware processing.

O(n·m)Transpose

Diagonal

Main diagonal: matrix[i][i]. Anti-diagonal: matrix[i][n-1-i]. Used in matrix rotation, palindrome detection on grids, and symmetry checks.

O(n)RotationSymmetry

Spiral

Four boundaries (top, bottom, left, right) shrink inward as each ring is traversed. Classic interview problem — requires careful boundary management to avoid revisiting cells.

O(n·m)BoundariesInterview classic
Walkthrough

Row-by-row on a 3×3 matrix

Matrix: [[1,2,3],[4,5,6],[7,8,9]] — visiting every cell left to right, top to bottom.

1

Row 0 — i=0, j=0,1,2

Visit [0][0]=1, [0][1]=2, [0][2]=3. j resets to 0. i increments to 1.

10,0
20,1
30,2
41,0
51,1
61,2
72,0
82,1
92,2
2

Row 1 — i=1, j=0,1,2

Visit [1][0]=4, [1][1]=5, [1][2]=6. Row complete.

1
2
3
41,0
51,1
61,2
7
8
9
3

Row 2 — i=2, j=0,1,2 → done

All 9 cells visited. Total iterations = 3×3 = 9 = O(n·m).

1
2
3
4
5
6
72,0
82,1
92,2
Python Code

All four patterns in code

PythonRow-by-row, Column-by-column, Diagonal
matrix = [[1,2,3],[4,5,6],[7,8,9]]
n, m = len(matrix), len(matrix[0])

# Row by row
for i in range(n):
    for j in range(m):
        print(matrix[i][j])

# Column by column (swap loop order)
for j in range(m):
    for i in range(n):
        print(matrix[i][j])

# Main diagonal (square matrix only)
for i in range(n):
    print(matrix[i][i])        # 1, 5, 9

# Anti-diagonal
for i in range(n):
    print(matrix[i][n-1-i])   # 3, 5, 7
PythonSpiral Order — shrinking boundaries
def spiral_order(matrix):
    result = []
    top, bottom = 0, len(matrix) - 1
    left, right  = 0, len(matrix[0]) - 1

    while top <= bottom and left <= right:
        for j in range(left, right + 1):    # → top row
            result.append(matrix[top][j])
        top += 1

        for i in range(top, bottom + 1):   # ↓ right col
            result.append(matrix[i][right])
        right -= 1

        if top <= bottom:
            for j in range(right, left - 1, -1):  # ← bottom row
                result.append(matrix[bottom][j])
            bottom -= 1

        if left <= right:
            for i in range(bottom, top - 1, -1):  # ↑ left col
                result.append(matrix[i][left])
            left += 1

    return result

Time & Space Complexity

All TraversalsO(n × m)Every cell visited exactly once regardless of pattern
Space — basicO(1)Just index variables — no extra array needed
Space — spiral resultO(n × m)Output array collects all n×m elements
Diagonal onlyO(min(n,m))Only visits the shorter dimension along the diagonal

Frequently asked questions

How do I check if an index is within bounds in a 2D array?

Check 0 <= row < len(matrix) and 0 <= col < len(matrix[0]). This is the bounds check used in BFS/DFS grid problems when exploring neighbours. Always check bounds before accessing matrix[row][col] to avoid IndexError.

How do I represent a graph as a 2D array?

An adjacency matrix is an n×n 2D array where matrix[i][j] = 1 means there's an edge from node i to node j. BFS and DFS on grids treat each cell as a node and its four neighbours (up, down, left, right) as adjacent nodes — this is the foundation of problems like Number of Islands and Shortest Path in Grid.

What are the four neighbours of a cell in a grid?

For cell (r, c), the four directional neighbours are (r-1, c) (up), (r+1, c) (down), (r, c-1) (left), (r, c+1) (right). Define a directions array [(-1,0),(1,0),(0,-1),(0,1)] and iterate over it — cleaner than four separate if-statements.

How do I rotate a matrix 90 degrees?

Clockwise 90°: first transpose the matrix (matrix[i][j] ↔ matrix[j][i]), then reverse each row. Anticlockwise 90°: reverse each row first, then transpose. Both are O(n²) time and O(1) space in-place. LeetCode 48 — Rotate Image.

What are common LeetCode problems on 2D arrays?

Spiral Matrix (LC 54), Rotate Image (LC 48), Number of Islands (LC 200), Set Matrix Zeroes (LC 73), Search a 2D Matrix (LC 74), Word Search (LC 79), and Game of Life (LC 289). Mastering row-by-row traversal and the four-direction neighbour pattern covers most of these.

Watch the grid cells light up in traversal order

Paste your 2D array into LearnBug and see every index update as the traversal moves across the grid.

Open Playground →