在做题中学习(90):螺旋矩阵II
解法:模拟
思路:创建相同大小的一个二维数组(矩阵),用变量标记原矩阵的行数和列数,每次遍历完一行或一列,相应行/列数--,进行对应位置的赋值即可。此题是正方形矩阵,因此不像螺旋矩阵I需要边界判断。
附上完整代码:
class Solution
{
public:
vector<vector<int>> generateMatrix(int n)
{
vector<vector<int>> ret(n,vector<int>(n));
int rows = n,cols = n;
int a = 0,b = -1,c = 1;
while(rows > 0 && cols > 0)
{
for(int i = 0;i<cols;i++)
ret[a][++b] = c++;
rows--;
for(int i = 0;i<rows;i++)
ret[++a][b] = c++;
cols--;
for(int i = 0;i<cols;i++)
ret[a][--b] = c++;
rows--;
for(int i = 0;i<rows;i++)
ret[--a][b] = c++;
cols--;
}
return ret;
}
};