# 59. Spiral Matrix II

Given a positive integer `n`, generate an `n x n` `matrix` filled with elements from `1` to `n2` in spiral order.

Example 1:

``````Input: n = 3
Output: [[1,2,3],[8,9,4],[7,6,5]]
``````

Example 2:

``````Input: n = 1
Output: [[1]]
``````

Constraints:

• `1 <= n <= 20`

``````class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> res(n, vector<int>(n));
int val = 1, p = n;
for (int i = 0; i < n / 2; ++i, p -= 2) {
for (int col = i; col < i + p; ++col)
res[i][col] = val++;
for (int row = i + 1; row < i + p; ++row)
res[row][i + p - 1] = val++;
for (int col = i + p - 2; col >= i; --col)
res[i + p - 1][col] = val++;
for (int row = i + p - 2; row > i; --row)
res[row][i] = val++;
}
if (n % 2 != 0) res[n / 2][n / 2] = val;
return res;
}
};
``````

``````class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> res(n, vector<int>(n));
int up = 0, down = n - 1, left = 0, right = n - 1, val = 1;
while (true) {
for (int j = left; j <= right; ++j) res[up][j] = val++;
if (++up > down) break;
for (int i = up; i <= down; ++i) res[i][right] = val++;
if (--right < left) break;
for (int j = right; j >= left; --j) res[down][j] = val++;
if (--down < up) break;
for (int i = down; i >= up; --i) res[i][left] = val++;
if (++left > right) break;
}
return res;
}
};
``````

Github 同步地址：

https://github.com/grandyang/leetcode/issues/59

Spiral Matrix

Spiral Matrix III

Spiral Matrix IV

https://leetcode.com/problems/spiral-matrix-ii/

https://leetcode.com/problems/spiral-matrix-ii/discuss/22392/C%2B%2B-template-for-Spiral-Matrix-and-Spiral-Matrix-II

https://leetcode.com/problems/spiral-matrix-ii/discuss/22289/My-Super-Simple-Solution.-Can-be-used-for-both-Spiral-Matrix-I-and-II

LeetCode All in One 题目讲解汇总(持续更新中…)

（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，快快加入吧～）

|

Venmo 打赏

—|—

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation