mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
24 lines
1017 B
Markdown
24 lines
1017 B
Markdown
![]() |
# [59. Spiral Matrix II](https://leetcode.com/problems/spiral-matrix-ii/)
|
|||
|
# 思路
|
|||
|
这题其实就是[54. Spiral Matrix](https://leetcode.com/problems/spiral-matrix)的一个特例,54题没问题的话这题就一点问题没有了,
|
|||
|
可参考[54题题解](https://github.com/ShusenTang/LeetCode/blob/master/solutions/54.%20Spiral%20Matrix.md)。
|
|||
|
|
|||
|
# C++
|
|||
|
``` C++
|
|||
|
class Solution {
|
|||
|
public:
|
|||
|
vector<vector<int>> generateMatrix(int n) {
|
|||
|
vector<vector<int>>res(n, vector<int>(n, 0));
|
|||
|
int num = 1;
|
|||
|
for(int i = 0; i < n / 2; i++){ // 一共有 n / 2 圈(不包括中间的那一个元素)
|
|||
|
for(int j = i; j <= n - i - 1; j++) res[i][j] = num++;
|
|||
|
for(int j = i + 1; j <= n - i - 1; j++) res[j][n - i -1] = num++;
|
|||
|
for(int j = n - i - 2; j >= i; j--) res[n - i - 1][j] = num++;
|
|||
|
for(int j = n - i - 2; j >= i + 1; j--) res[j][i] = num++;
|
|||
|
}
|
|||
|
if(n % 2) res[n / 2][n / 2] = num; // 若n是奇数
|
|||
|
return res;
|
|||
|
}
|
|||
|
};
|
|||
|
```
|