59. 螺旋矩阵 II
给你一个正整数 n
,生成一个包含 1
到 n2
所有元素,且元素按顺时针顺序螺旋排列的 n x n
正方形矩阵 matrix
。
分析
一轮赋值顺序: 避免重复赋值,每一次的终点不赋值 n=3为例[1,3)
左上----->右上 右上----->右下 右下------>左下 左下------>左上
需要几轮赋值?也就是循环的次数--> n/2
如果n为奇数,中间多一个需要单独赋值
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> ans(n, vector<int>(n,0));
int leftTopX = 0, leftTopY=0; //每轮左上角坐标
int num = 1; //用于赋值
int loop = n/2; //循环次数
int offset = 1;
if(n%2 == 1){ //对于奇数 给中间位置单独赋值
ans[n/2][n/2] = n*n;
}
while(loop){
loop--;
int row = leftTopX++;
int col = leftTopY++;
for(col; col<n-offset; col++){ //左上----->右上
ans[row][col] = num++;
}
for(row; row<n-offset; row++){ // 右上----->右下
ans[row][col] = num++;
}
for(col; col > 0+offset-1; col--){ //右下------>左下
ans[row][col] = num++;
}
for(row; row > 0+offset-1; row--){ //左下------>左上
ans[row][col] = num++;
}
offset++;
}
return ans;
}
剑指 Offer 29. 顺时针打印矩阵
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
示例 1:
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]
分析:
按顺时针遍历,先确定上下左右边界,每遍历一轮边界收缩。每轮中左闭右开加入元素
输入矩阵不一定时正方形,可能会剩下一行或者一列单独处理
vector<int> spiralOrder(vector<vector<int>>& matrix) {
if(matrix.size() == 0 || matrix[0].size() == 0)
return {};
vector<int> ans;
int left = 0, right = matrix[0].size()-1;//确定边界
int top = 0, bottom = matrix.size()-1;
int num = matrix.size()*matrix[0].size();
while( left<right && top<bottom ){ //顺时针遍历,按[ ,)加入元素
int col,row;
for(row = top, col = left; col<right; col++){
ans.push_back( matrix[row][col]);
}
for(row = top, col = right; row<bottom; row++){
ans.push_back( matrix[row][col]);
}
for(row = bottom, col = right; col>left; col--){
ans.push_back( matrix[row][col]);
}
for(row = bottom, col = left; row>top; row--){
ans.push_back( matrix[row][col]);
}
left++;
top++;
right--;
bottom--;
}
if (top == bottom) { // 剩下一行,从左到右依次添加
for (int i = left; i <= right; i++) {
ans.push_back(matrix[top][i]);
}
} else if (left == right) { // 剩下一列,从上到下依次添加
for (int i = top; i <= bottom; i++) {
ans.push_back(matrix[i][left]);
}
}
return ans;
}