DSA Tracker

DSA Tracker

Topic Lesson

Learn Matrix from scratch

A complete 4-step path: handwritten notebook primer, animated visualizer, speed check quiz, and compiler practice.

What is Matrix

notebook note

A matrix is a flat grid of cells laid out in rows and columns, like a checkerboard or a spreadsheet. Each cell has an address made of two numbers: its row index going down and its column index going across. Because computer memory stores these rows one after another or as arrays of arrays, jumping straight to any individual cell takes the same tiny fraction of time no matter where it sits on the board.

When to reach for it

Reach for matrix techniques when the input is a two-dimensional grid, board, or map. Common prompts include walking through a maze, finding connected islands of land in water, rotating an image ninety degrees in place, or reading numbers in a spiral. Words like rows, columns, neighbors, adjacent squares, or diagonal lines are clear signs. It also appears in grid planning where each cell depends on the values above and to the left.

How to think about it

Think of navigating the grid using directional coordinate offsets. Define row and column step arrays for moving up, down, left, and right. Always check that new row and column indices stay strictly between zero and the board boundaries before reading cell values. For spiral scans, track four boundary lines for top, bottom, left, and right, shrinking them inward after reading each side. When searching connected regions, mark visited cells directly or write a marker value into the cell to avoid looping.

Operation costs

measured big-O
OperationTime
read or write cell by row and columnO(1)
visit every cell across m rows and n columnsO(m * n)
rotate square matrix in placeO(n^2)

Common mistakes to avoid

  • Flipping row and column dimensions by mixing up grid height with grid width, causing index out of bounds crashes on rectangular grids where row and column counts differ.
  • Reading neighbor cells without first confirming that the row and column coordinates are within valid bounds between zero and the board edges.
  • Forgetting to update inner boundary limits during spiral traversal, which causes single-row or single-column matrices to print duplicate entries.
Step 1 of 4