题目:
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
思路:
题意是按照顺时针一层一层打印出一个n*n的矩阵。思路就是分清楚四个边界,然后每打印一层,就更新相对应层的值。如原本up是0,down是n-1,打印完第一行,up就应该变1;打印完最后一行,down就应该变n-2。最后注意循环跳出情况,当up>down时跳出,而不是up>=down,因为偶数时,up在第二层,down在第三层时,down的那层是还没打印的。
代码:
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
if(n==0)
return {};
vector<vector<int>> f(n,vector<int>(n));
int cur=1;
int left=0, right=n-1, up=0,down=n-1;
while(1)
{
for(int i=left;i<=right;i++)
f[up][i]=cur++;
up++;
if(up>down)
break;
for(int i=up;i<=down;i++)
f[i][right]=cur++;
right--;
if(left>right)
break;
for(int i=right;i>=left;i--)
f[down][i]=cur++;
down--;
if(up>down)
break;
for(int i=down;i>=up;i--)
f[i][left]=cur++;
left++;
if(left>right)
break;
}
return f;
}
};