1、题目描述
Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
Example:
Input: 3
Output:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
2、问题描述:
- 螺旋填充一个矩阵。
3、问题关键:
- 螺旋矩阵1
- 方向,坐标更新,边界条件。
4、C++代码:
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> res(n, vector<int>(n, 0));
int dx[4] = {0, 1, 0, -1}, dy[4] = {1, 0, -1, 0};
if (!n) return res;
int x = 0, y = 0, d = 0;
for (int i = 0; i < n * n; i ++) {
int a = x + dx[d], b = y + dy[d];
if (a < 0 || a >= n || b < 0 || b >= n || res[a][b]) {
d = (d + 1) % 4;
a = x + dx[d], b = y + dy[d];
}
res[x][y] = i + 1;
x = a, y = b;
}
return res;
}
};