Spiral Matrix II

Generate an n-by-n matrix filled 1..n^2 by walking the same four-direction spiral as Spiral Matrix.

Medium
Time O(n^2) Space O(n^2)
LeetCode
5 min read
matrix simulation

Problem#

Given a positive integer n, return an n x n matrix filled with 1 to n^2 in spiral order, starting from the top-left moving right.

Examples#

  • n = 3[[1,2,3],[8,9,4],[7,6,5]]
  • n = 1[[1]]

Constraints#

  • 1 <= n <= 20.

Approach#

Mirror the Spiral Matrix walk: maintain top, bottom, left, right bounds and a running counter. Fill each side, shrink the corresponding bound, repeat.

Solution#

Spiral Matrix II
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> a(n, vector<int>(n, 0));
int top = 0, bottom = n - 1, left = 0, right = n - 1, v = 1;
while (top <= bottom && left <= right) {
for (int j = left; j <= right; ++j) a[top][j] = v++;
++top;
for (int i = top; i <= bottom; ++i) a[i][right] = v++;
--right;
if (top <= bottom) {
for (int j = right; j >= left; --j) a[bottom][j] = v++;
--bottom;
}
if (left <= right) {
for (int i = bottom; i >= top; --i) a[i][left] = v++;
++left;
}
}
return a;
}
};

Editorial#

For square matrices the bound checks technically aren’t strictly needed in the bottom/left pass when both dimensions shrink in lockstep, but keeping them ensures correctness if n ever becomes 1 (a single cell must be written exactly once).

Complexity#

  • Time: O(n^2).
  • Space: O(n^2).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.