C++刷leetcode(59. 螺旋矩阵 II)【数据结构】【越界判断】
题目描述:给定一个正整数 n,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。
示例:
输入: 3
输出:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/spiral-matrix-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int> > res(n, vector<int>(n, 0));
int left = 0, right = n-1;
int up = 0, down = n-1;
int number = 1;
while(left <= right && up <= down){
for(int i = left; i <= right; i++){
res = number++;
}
up++;
if(up > down) break;
for(int i = up; i <= down; i++){
res = number++;
}
right--;
if(left > right) break;
for(int i = right; i >= left; i--){
res = number++;
}
down --;
if(up > down) break;
for(int i = down; i >= up; i--){
res = number++;
}
left++;
if(left > right) break;
}
return res;
}
};
页:
[1]