Rows first: matrix[r][c]
matrix[r] is a whole row; matrix[r][c] is one value in it. So the first index picks the row (how far down) and the second the column (how far across). len(matrix) is the number of rows and len(matrix[0]) the number of columns.
| 0 | 1 | 2 | |
|---|---|---|---|
| 0 | 11 | 22 | 33 |
| 1 | 48 | 59 | 64 |
| 2 | 77 | 86 | 95 |
Spiral order: four walls closing in
Spiral order reads the top row left to right, the right column downward, the bottom row right to left and the left column upward, then does the same one ring further in. Four variables, top, bottom, left and right, are the walls of the part not yet read. Each side that is read moves its wall one step inward, and the loop stops when the walls cross. The two if checks stop a single remaining row or column from being read twice.
def spiralOrder(matrix):
result = []
top, bottom = 0, len(matrix) - 1
left, right = 0, len(matrix[0]) - 1
while top <= bottom and left <= right:
for c in range(left, right + 1):
result.append(matrix[top][c])
top += 1
for r in range(top, bottom + 1):
result.append(matrix[r][right])
right -= 1
if top <= bottom:
for c in range(right, left - 1, -1):
result.append(matrix[bottom][c])
bottom -= 1
if left <= right:
for r in range(bottom, top - 1, -1):
result.append(matrix[r][left])
left += 1
return result
Rotating in place: transpose, then reverse
To rotate a square matrix 90° clockwise without a second matrix, first transpose it (swap matrix[i][j] with matrix[j][i], so rows become columns), then reverse each row. The inner loop starts at i + 1 so that each pair is swapped once; start it at 0 and every swap is undone.
| 0 | 1 | 2 | |
|---|---|---|---|
| 0 | 7 | 4 | 1 |
| 1 | 8 | 5 | 2 |
| 2 | 9 | 6 | 3 |
def rotate(matrix):
n = len(matrix)
for i in range(n):
for j in range(i + 1, n):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
for i in range(n):
matrix[i].reverse()
return matrix
What you see in PyVisualizer
A list of lists is drawn as a grid with its row and column indices. The variables that index it are drawn on it: left and right under their columns, and the cell a line reads, such as matrix[top][c], outlined and named (top, c). The columns that left and right stand on are tinted, and result fills in below the grid. When two walls meet on the same row or column, their names are shown from opposite sides, so neither hides the other.
Common mistakes
- Swapping the indices:
matrix[c][r]instead ofmatrix[r][c]. On a square matrix it runs and gives a wrong answer; on any other it raisesIndexError. - Using len(matrix) for the columns of a matrix that is not square.
- Building it with [[0] * n] * n, which makes every row the same list. See Python references explained.
Try it yourself
- Run spiral order on a 3 × 4 matrix, such as [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]].
- Paste a grid search, like number of islands or word search, and give the grid as a list of lists.