59
给你一个正整数 n ,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。
示例 1:
1 2 3
8 9 4
7 6 5
输入:n = 3
输出:[[1,2,3],[8,9,4],[7,6,5]]
示例 2:
输入:n = 1
输出:[[1]]
思路:
要控制每一条边的边界取值,取左闭右开,模拟顺时针画矩阵的过程
class Solution
{
public:
vector<vector<int>> generateMatrix(int n){
vector<vector<int>>res(n,vector<int>(n,0)); //定义一个二维数组
int mid=n/2; //中间位置
int startx=0,starty=0; //每一圈的起始位置
int i,j;
int count=1;
int offset=n/2;
int loop=n/2; //每一圈循环的次数,就是一共有多少圈
while(loop--)
{
i=startx;
j=starty;
for(j=starty;j<starty+n-offset;j++)
{
res[stratx][j]=count++;
}
for(i=startx;i<startx+n-offset;i++)
{
res[i][j]=count++;
}
for(;j>starty;j--)
{
res[i][j]=count++;
}
for(;i>startx;i--)
{
res[i][j]=count++;
}
startx++;
starty++; //到下一圈要到新的起始位置比如(1,1)
offset+=2;
}
if(n%2!=0)
{
res[mid][mid]=-count; //给最中间的值赋值
}
return res;
}
};
顺时针打印矩阵
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
示例 1:
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]
示例 2:
输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
输出:[1,2,3,4,8,12,11,10,9,5,6,7]
限制:
0 <= matrix.length <= 100
0 <= matrix[i].length <= 100
思路:
很显然需要一个一维数组来存储最终的结果
这个可以也是参照上图的例子来从最外层逐步求解
遍历顺序:
上:top,left-----------top,right
右:top+1,right------bottom,right
下:bottom,right-1–bottom,left+1
左:bottom,left----top+1,left
class Solution
{
publc:
vector<int> spiralOrder(vector<vector<int>> &Matrix)
{
vector<int> order;
int rows=matrix.size();
int columns=matrix[0].size();
int top=0,right=columns-1,left=0,bottom=rows-1;
while(left<=right && top<=bottom)
{
for(int column=left;column<=right;column++)
{
order.push_back(matrix[top][column]);
}
for(int row=top+1;row<=bottom;row++)
{
order.push_back(matrix[row][right]);
}
if(left<right && top< bottom)
{
for(int column=right-1;column>left;column--)
{
order.push_back(matrix[bottom][column]);
}
for(int row=bottom;row>top;row--)
{
order.push_back(matrix[row][left]);
}
}
top++;
left++;
right--;
bottom--;
}
return order;
}
};