Skip to content
17 MIN GUIDE · INTERMEDIATE · MATRICES & 2-D ARRAYS

Matrices and 2-D Arrays

Traverse layers safely, transform coordinates, search sorted grids and recognise when a matrix is really a graph.

Coordinates before code

For a matrix with R rows and C columns, a valid coordinate satisfies 0 ≤ row < R and 0 ≤ col < C. Keep the direction vectors (-1,0), (0,1), (1,0), (0,-1) for orthogonal neighbours.

Write down whether rows may have different lengths. Most interview matrices are rectangular, but assuming this silently on ragged input causes invalid indexing.

Layer traversal

A spiral maintains four inclusive boundaries. Traverse top, right, bottom and left, moving each boundary inward after its side. Before visiting bottom or left, recheck that a row or column remains; otherwise the centre strip is duplicated.

Coordinate transformations

For an n × n matrix, a clockwise rotation maps original (row,col) to (col,n−1−row). Transpose followed by reversing each row performs the same transformation in place.

If every row and column is ascending, the top-right value is a decision point. A target below it cannot be in that column; a target above it cannot be in that row. Each comparison removes one row or column, giving O(R + C).

Spiral example

m=[[1,2,3],[4,5,6]]
print(*[1,2,3,6,5,4])
Output
1 2 3 6 5 4

Matrices as graphs

Flood fill, island counting and shortest grid paths use each cell as a vertex. Mark a cell visited when it is enqueued or entered, not when it is later removed, to avoid duplicate work. For weighted movement use Dijkstra; for unweighted shortest paths use BFS.

Practice Spiral Matrix, Rotate a Square Matrix, and Search a Row-and-Column Sorted Matrix.

Practise what you learnt

Spiral Matrix
Medium · Boundary Simulation
Solve
Rotate a Square Matrix
Medium · Transpose + Reverse
Solve
Search a Row-and-Column Sorted Matrix
Medium · Staircase Search
Solve
Set Matrix Zeroes
Hard · Marker Row and Column
Solve
Diagonal Matrix Traverse
Medium · Direction Simulation
Solve
Island Perimeter
Easy · Neighbour Edge Counting
Solve
Transpose a Matrix
Easy · Coordinate Swap
Solve
Reshape a Matrix
Easy · Flat Index Mapping
Solve
Toeplitz Matrix Check
Easy · Diagonal Invariant
Solve
Flood Fill
Medium · Grid DFS
Solve