原题连接:Leetcode 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
方法一:模拟
思路:
模拟呗,设置四个方向
每次判断下一格是否越界,越界就转向
c++代码:
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
// maxn最大值 cur当前值
int maxn = n * n, cur = 1;
// 方向: 右下左上
vector<vector<int>> direction = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
vector<vector<int>> ans(n, vector<int>(n));
// xy坐标 i方向的下标
int x = 0, y = 0, i = 0;;
while(cur <= maxn){
ans[x][y] = cur;
cur++;
// 若果下一个方向越界 或者碰到了已经填过数的格子 将方向转向
int next_x = x + direction[i][0], next_y = y + direction[i][1];
if(next_x < 0 || next_x >= n || next_y < 0 || next_y >= n || ans[next_x][next_y] != 0){
i = (i + 1) % 4;
}
x = x + direction[i][0];
y = y + direction[i][1];
}
return ans;
}
};
复杂度分析:
- 时间复杂度:O(n2),循环进行n2次
- 空间复杂度:O(1),常数个临时变量