Arrays & Hashing · Pattern 15 of 26
Matrix traversal: spirals and diagonals
Walk a grid in a non-obvious order. Spirals peel off layers using four shrinking boundaries; diagonals group cells by i + j (or i − j).
Watch the lesson
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
When to use it
- Print or visit a matrix in spiral or zigzag order
- Every cell on the same diagonal shares a property
- Distances that split into a row part and a column part
The template
int[] spiralOrder(int[][] m) {
List<Integer> out = new ArrayList<>();
int top = 0, bottom = m.length - 1, left = 0, right = m[0].length - 1;
while (top <= bottom && left <= right) {
for (int j = left; j <= right; j++) out.add(m[top][j]);
top++;
for (int i = top; i <= bottom; i++) out.add(m[i][right]);
right--;
if (top <= bottom) { for (int j = right; j >= left; j--) out.add(m[bottom][j]); bottom--; }
if (left <= right) { for (int i = bottom; i >= top; i--) out.add(m[i][left]); left++; }
}
return out.stream().mapToInt(Integer::intValue).toArray();
} def spiral_order(m):
out = []
top, bottom, left, right = 0, len(m) - 1, 0, len(m[0]) - 1
while top <= bottom and left <= right:
out += [m[top][j] for j in range(left, right + 1)]
top += 1
out += [m[i][right] for i in range(top, bottom + 1)]
right -= 1
if top <= bottom:
out += [m[bottom][j] for j in range(right, left - 1, -1)]
bottom -= 1
if left <= right:
out += [m[i][left] for i in range(bottom, top - 1, -1)]
left += 1
return out vector<int> spiralOrder(vector<vector<int>>& m) {
vector<int> out;
int top = 0, bottom = (int)m.size() - 1, left = 0, right = (int)m[0].size() - 1;
while (top <= bottom && left <= right) {
for (int j = left; j <= right; j++) out.push_back(m[top][j]);
top++;
for (int i = top; i <= bottom; i++) out.push_back(m[i][right]);
right--;
if (top <= bottom) { for (int j = right; j >= left; j--) out.push_back(m[bottom][j]); bottom--; }
if (left <= right) { for (int i = bottom; i >= top; i--) out.push_back(m[i][left]); left++; }
}
return out;
} function spiralOrder(m) {
const out = [];
let top = 0, bottom = m.length - 1, left = 0, right = m[0].length - 1;
while (top <= bottom && left <= right) {
for (let j = left; j <= right; j++) out.push(m[top][j]);
top++;
for (let i = top; i <= bottom; i++) out.push(m[i][right]);
right--;
if (top <= bottom) { for (let j = right; j >= left; j--) out.push(m[bottom][j]); bottom--; }
if (left <= right) { for (let i = bottom; i >= top; i--) out.push(m[i][left]); left++; }
}
return out;
} The variations
-
1Peel the layers
Four boundaries; take the top row, right column, bottom row, left column, shrinking a boundary after each side.
-
2Walk the diagonals
Cells with the same i + j form an anti-diagonal; the same i − j, a diagonal. Group by that key, reversing every other group for a zigzag.
Now you solve -
3Rows and columns separately
Manhattan distance splits into a row part and a column part, so the best meeting point is the median row and median column. Sparse multiplication skips zero rows.
Now you solve
Mistakes to avoid
- Missing the two
ifchecks in the spiral: a single remaining row or column gets printed twice. - Mixing up rows and columns on non-square matrices.
Lesson done
Next: The Josephus elimination recurrence →Mark it done once you can write the template from memory and you have solved the worked examples yourself.