0%

54.螺旋矩阵

54. 螺旋矩阵

给你一个 mn 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。

示例 1:

img

输入: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]

提示:

  • m == matrix.length
  • n == matrix[i].length
  • 1 <= m, n <= 10
  • -100 <= matrix[i][j] <= 100

C++

class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> res;
int top = 0, bottom = matrix.size() - 1;
int left = 0, right = matrix[0].size() - 1;
while(true){
for(int col = left; col <= right; col ++){
res.push_back(matrix[top][col]);
}if(++ top > bottom) break;
for(int row = top; row <= bottom; row ++){
res.push_back(matrix[row][right]);
}if(-- right < left) break;
for(int col = right; col >= left; col --){
res.push_back(matrix[bottom][col]);
}if(-- bottom < top) break;
for(int row = bottom; row >= top; row --){
res.push_back(matrix[row][left]);
}if(++ left > right) break;
}
return res;
}
};

59. 螺旋矩阵 II

给你一个正整数 n ,生成一个包含 1n2 所有元素,且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix

示例 1:

img

输入:n = 3
输出:[[1,2,3],[8,9,4],[7,6,5]]

示例 2:

输入:n = 1
输出:[[1]]

提示:

  • 1 <= n <= 20

C++

class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> res(n,vector<int>(n, 0));
int top = 0, bottom = n - 1, left = 0, right = n - 1;
int num = 1;
while(true){
for(int col = left; col <= right; col ++){
res[top][col] = num ++;
} top ++;
if(num > n*n) break;

for(int row = top; row <= bottom; row ++){
res[row][right] = num ++;
} right --;
if(num > n*n) break;

for(int col = right; col >= left; col --){
res[bottom][col] = num ++;
} bottom --;
if(num > n*n) break;

for(int row = bottom; row >= top; row --){
res[row][left] = num ++;
} left ++;
if(num > n*n) break;
}
return res;
}
};