20.12.10 59. 螺旋矩阵Ⅱ
作者:互联网
题目
给定一个正整数 n,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。
示例:
输入: 3
输出:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
思路
- 跟上一题一样,也是这个模拟螺旋过程,把对应数字放回对应位置即可
代码
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
int left = 0, right = n-1, top = 0, bottom = n-1;
vector<vector<int>> ans(n, vector<int>(n));
int num = 1;
while(left <= right || top <= bottom){
for(int i = left; i < right+1; ++i, ++num)
ans[top][i] = num;
if(++top > bottom) break;
for(int i = top; i < bottom+1; ++i, ++num)
ans[i][right] = num;
if(--right < left) break;
for(int i = right; i > left-1; --i, ++num)
ans[bottom][i] = num;
if(--bottom < top) break;
for(int i = bottom; i > top-1; --i, ++num)
ans[i][left] = num;
if(++left > right) break;
}
return ans;
}
};
标签:10,right,59,bottom,int,num,ans,20.12,left 来源: https://www.cnblogs.com/wasi-991017/p/14111874.html