LeetCode/solutions/59. Spiral Matrix II.md
2019-02-01 21:34:40 +08:00

24 lines
1017 B
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# [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;
}
};
```