Data Structures
Matrix (2D Grid)
Read/write a cell: O(1) · Visit every cell: O(rows × cols) · Transpose: O(rows × cols), since every cell is copied exactly once.
The idea, in plain English
A matrix is like a spreadsheet. It has rows and columns of cells. You find every cell using two numbers instead of one: its row and its column. Under the hood, it's usually just 'a list of lists.' The outer list holds the rows. Each row is itself a list of cell values.
How it works
- 1Build a grid of rows and columns, each cell reachable as grid[row][col].
- 2Read or write a cell directly using its row and column index.
- 3Walk the whole grid with a nested loop: an outer loop over rows, an inner loop over columns.
- 4Transpose flips rows into columns: the value at [row][col] moves to [col][row] in a new grid.
When you'd use it
Use a matrix for anything laid out on a grid: spreadsheets, game boards like chess, Tic-Tac-Toe, or Minesweeper, images made of rows of pixels, or grid-based pathfinding maps.
Common beginner mistakes
- Don't swap row and column by accident. grid[row][col] and grid[col][row] are usually different cells, unless the grid is square and symmetric.
- Don't assume every row has the same length after building a grid by hand. A 'ragged' 2D array, with rows of different lengths, will break code that expects a clean rectangle.
Try it — edit and run
Click the code to edit · press ⌘/Ctrl+↵ to run
Editable code. Tab and Shift+Tab indent. Press Escape, then Tab, to move focus out of the editor.
Grid: 1 2 3 | 4 5 6
Cell (1,2): 6
Row 0 sum: 6
Transposed: 1 4 | 2 5 | 3 6See it in motion
Ready. Press play — address a cell, walk every cell, then transpose across the diagonal.
Not sure this is the right topic? See the learning paths → or where this leads →