文章目录
一、题目
54. Spiral Matrix
Given an m x n matrix, return all elements of the matrix in spiral order.
Example 1:
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [1,2,3,6,9,8,7,4,5]
Example 2:
Input: matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
Output: [1,2,3,4,8,12,11,10,9,5,6,7]
Constraints:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 10
-100 <= matrix[i][j] <= 100
二、题解
确定边界,进行模拟
cpp
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
int m = matrix.size();
int n = matrix[0].size();
vector<int> res;
//左边界,右边界,上边界,下边界
int left = 0,right = n - 1,up = 0,down = m - 1;
while(true){
//从左到右
for(int j = left;j <= right;j++) res.push_back(matrix[up][j]);
//上边界下移
if(++up > down) break;
//从上到下
for(int i = up;i <= down;i++) res.push_back(matrix[i][right]);
//右边界左移
if(--right < left) break;
//从右到左
for(int j = right;j >= left;j--) res.push_back(matrix[down][j]);
//下边界上移
if(--down < up) break;
//从下到上
for(int i = down;i >= up;i--) res.push_back(matrix[i][left]);
//左边界右移
if(++left > right) break;
}
return res;
}
};