给定一个正整数 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:
void helper(vector<vector<int>>&nums, int i,int j,int n,int &tmp){
int r,c;
for(r=i,c=j;c<n-j;++c){
nums[r][c] = tmp;
tmp++;
}
//cout<<"1 "<<tmp<<endl;
for( c = n-j-1,r=r+1;r<n-i;r++){
nums[r][c] = tmp;
tmp++;
}
//cout<<"2 "<<tmp<<endl;
for(c = c-1,r=n-i-1;c>=j;--c){//注意列c的取值范围
nums[r][c] = tmp;
tmp++;
}
//cout<<"3 "<<tmp<<endl;
for(r=n-i-2,c=j;r>i;--r){
nums[r][c] = tmp;
tmp++;
}
//cout<<"4 "<<tmp<<endl;
}
vector<vector<int>> generateMatrix(int n) {
if(n<=0){
return {{}};
}
if(n==1){
return {{1}};
}
vector<vector<int>>nums(n,vector<int>(n,1));
int i,j;
int tmp=1;
for(i=0,j=0;i<n-i-1;++j,++i){
helper(nums,i,j,n,tmp);
}
if(i==n-i-1){
nums[i][j] = n*n;
}
return nums;
}
};
作者:he-zi-11
链接:https://leetcode-cn.com/problems/spiral-matrix-ii/solution/he-xuan-zhuan-ju-zhen-ide-jie-fa-lei-si-du-shi-zui/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。