题目描述
给定一个正整数 n,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。
示例:
输入: 3 输出: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
问题分析
此题先创建一个n乘n的数组ans,然后像leetcode54题一样,顺时针遍历整个数组,只不过不同的是在遍历到每一个元素的时候,将它赋值。当遍历到n乘n这个数也赋值之后,就说明已经全部赋值完毕,返回ans数组即可。
代码实现
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> ans(n, vector<int>(n, 0));
string dir = "right";
int rowup = 0;
int colleft = 0;
int rowdown = n - 1;
int colright = n - 1;
int val = 1;
int target = n * n;
int i = 0;
int j = 0;
while(j <= colright || i <= rowdown || j >= colleft || i >= rowup){
if(dir == "right"){
while(j <= colright){
ans[i][j] = val;
j++;
val++;
if(val == target + 1)
return ans;
}
j--;
i++;
rowup++;
dir = "down";
}
else if(dir == "down"){
while(i <= rowdown){
ans[i][j] = val;
i++;
val++;
if(val == target + 1)
return ans;
}
i--;
j--;
colright--;
dir = "left";
}
else if(dir == "left"){
while(j >= colleft){
ans[i][j] = val;
j--;
val++;
if(val == target + 1)
return ans;
}
j++;
i--;
rowdown--;
dir = "up";
}
else{
while(i >= rowup){
ans[i][j] = val;
i--;
val++;
if(val == target + 1)
return ans;
}
i++;
j++;
colleft++;
dir = "right";
}
}
return ans;
}
};