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.
Sorted-grid search
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])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
Medium · Boundary Simulation
Medium · Transpose + Reverse
Medium · Staircase Search
Hard · Marker Row and Column
Medium · Direction Simulation
Easy · Neighbour Edge Counting
Easy · Coordinate Swap
Easy · Flat Index Mapping
Easy · Diagonal Invariant
Medium · Grid DFS