Courses / DSA Patterns for Working Engineers / Chapter 18
Module 6 · Matrices, stacks and graphs · Chapter 18 of 39
Matrices: Traversals, Rotations and In-Place Marking
Builds on The Coding Interview: How the Round Runs and How to Prepare. Next up: Stacks: Matching, Parsing and Nested Structure.
Part 1 · Introduction to matrices
Rows, columns and indexes
Seating charts, warehouse shelves, game boards and image pixels are all grids. Most grid problems come down to indexing: staying inside the edges and never swapping a row for a column.
A matrix, or grid, is an array of rows. m[r][c] is the cell in row r and column c, counting from 0 at the top left. The number of rows is m.length and the number of columns is m[0].length, assuming the grid has at least one row and every row has the same length. Rows run down and columns run across, so m[1][3] is the second row, fourth column.
The same grid can live in one flat array. In row-major order the cells of row 0 come first, then row 1, and so on, so the cell at (r, c) is at flat index r * cols + c. Going back, the row is Math.floor(i / cols) and the column is i % cols. A flat typed array such as Int8Array uses less memory than an array of arrays and makes copying a single call, at the price of doing that arithmetic.
// One flat array holding a rows by cols grid in row-major order. export const toIndex = (r: number, c: number, cols: number) => r * cols + c export const toCell = (i: number, cols: number): [number, number] => [ Math.floor(i / cols), i % cols, ]
The demo makes a grid of 3 rows and 4 columns as an Int8Array, stores 5 at row 2, column 1, and maps index 9 back to a cell.