Creating and traversing matrices
A matrix is a list of lists: each inner list is a row. It is accessed with m[row][column] . This lesson assumes you know the…
Grids are everywhere: boards, images, maps, spreadsheets. In this lesson you will work with matrices as lists of lists: traverse them by rows and columns, transpose and rotate them, move along diagonals and neighbors, walk them in a spiral, count regions with a flood fill and multiply them. You will learn to watch the bounds and to avoid the shared-rows mistake.
A matrix is a list of lists: each inner list is a row. It is accessed with m[row][column] . This lesson assumes you know the…
Almost every matrix transformation is written with zip(*m) (transpose) and the slicing [::-1] (reverse). Combining them gives…
Many grid problems require moving between squares. The standard technique is to store the possible offsets in a list and always…
A matrix of characters or of zeros and ones often represents a map . Typical questions are how many connected regions there are…
The matrix product combines rows of the first with columns of the second: element (i, j) is the sum of a[i][k] * b[k][j] . It can…
A matrix is a list of lists. Summing each row is direct with sum(row) ; for the columns, zip(*m) transposes it.
The transpose of a matrix swaps rows and columns: the element at row i and column j moves to row j and column i .
Rotating a matrix 90° clockwise is equivalent to reversing the order of the rows and transposing . After rotating, a matrix of f…
In a square matrix, the main diagonal runs from top left to bottom right ( m[i][i] ) and the secondary one from top right to…
Traversing a matrix in a spiral means reading the first row, going down the last column, coming back along the last row and going…
A square matrix is symmetric if it equals its transpose: element m[i][j] matches m[j][i] .
To multiply A ( n × m ) by B ( m × p ), each element of the result is the dot product of a row of A by a column of B . The result…
In minesweeper , each square without a mine shows how many mines there are in its up to 8 neighbouring squares. You must take…
The paint bucket tool of an image editor changes the colour of a square and of every connected square (horizontally or…
A magic square is a square matrix in which all rows, all columns and both diagonals add up to the same value.