给你一个正整数 n
,生成一个包含 1
到 n2
所有元素,且元素按顺时针顺序螺旋排列的 n x n
正方形矩阵 matrix
。
-------------------------------------------------------------------------------------------------------------------
方法1
模拟矩阵的生成。按照要求,初始位置设为矩阵的左上角,初始方向设为向右。若下一步的位置超出矩阵边界,或者是之前访问过的位置,则顺时针旋转,进入下一个方向。如此反复直至填入 n*n个元素。记 matrix 为生成的矩阵,其初始元素设为 0。由于填入的元素均为正数,我们可以判断当前位置的元素值,若不为 0,则说明已经访问过此位置。需要建立一个方向矩阵
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>>matrix(n,vector<int>(n));
int num=1;
int maxnum=n*n;
int row=0;
int column=0;
int iddriect=0;
vector<vector<int>>direction={{0,1},{1,0},{0,-1},{-1,0}};//右下左上
while(num<=maxnum)
{
matrix[row][column]=num;
num++;
int nextrow=row+direction[iddriect][0];
int nextcolumn=column+direction[iddriect][1];
if(nextrow<0||nextrow>=n||nextcolumn<0||nextcolumn>=n||matrix[nextrow][nextcolumn]!=0)
{
iddriect=(iddriect+1)%4;//不要忘记取余
}
row=row+direction[iddriect][0];
column=column+direction[iddriect][1];
}
return matrix;
}
};
方法2
官方解:
1.从左到右填入上侧元素,依次为(top,left) 到 )(top,right)。
2.从上到下填入右侧元素,依次为 (top+1,right) 到(bottom,right)。
3.如果 left<right 且 top<bottom,则从右到左填入下侧元素,依次为 (bottom,right−1) 到 (bottom,left+1)
4.以及从下到上填入左侧元素,依次为(bottom,left) 到 (top+1,left)。
但是个人认为,第三步的判断left<right 且 top<bottom可以提前到第二步,这是因为出现left!<right 且 top!<bottom的情况应该只有在这一层只有一个位置需要填充的时候才会发生,所以只要保证在这个判断之前程序已经填充了一个元素即可,把其放在第三个位置,如果出现了一层只有一个位置需要填充的情况,第二步的代码也不会执行,为了减少代码执行量不如将left<right 且 top<bottom这一判断放在第二步,可以在执行后面三步,改过后的代码执行没有错误(个人见解,不知对错)
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
int num = 1;
vector<vector<int>> matrix(n, vector<int>(n));
int left = 0, right = n - 1, top = 0, bottom = n - 1;
while (left <= right && top <= bottom) {
for (int column = left; column <= right; column++) {
matrix[top][column] = num;
num++;
}
if (left < right && top < bottom) {
for (int row = top + 1; row <= bottom; row++) {
matrix[row][right] = num;
num++;
}
for (int column = right - 1; column > left; column--) {
matrix[bottom][column] = num;
num++;
}
for (int row = bottom; row > top; row--) {
matrix[row][left] = num;
num++;
}
}
left++;
right--;
top++;
bottom--;
}
return matrix;
}
};