54. Spiral Matrix
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
Example 1:
Input:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
Output: [1,2,3,6,9,8,7,4,5]
Example 2:
Input:
[
[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]
方法1: Layer-by-Layer
官方题解:https://leetcode.com/problems/spiral-matrix/solution/
思路:
用四个变量标记上下左右的边界,每次遍历过一条边之后都将这一行/列排除。比如遍历完红色边之后firstRow下移,遍历绿色之后,lastCol左移,etc。循环条件就是firstRow <= lastRow, firstCol <= lastCol。当然这是不够的,还要在每次循环的中间随时判断是否break。以下图为栗子,边界条件出现在图二画出的情况。也就是说,只要当挪动某一行之后发现first/last的顺序被颠倒了,不管是行还是列,说明都刚刚遍历完了最内层,没有必要再继续,随时break。究竟哪个方向先break取决于长方形的形状。
易错点
- 循环内部的退出条件
Complexity
Time complexity: O(N), where N is the total number of elements in the input matrix. We add every element in the matrix to our final answer.
Space complexity: O(N), the information stored in ans.
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> result = {};
if (matrix.empty() || matrix[0].empty()) return result;
int firstRow = 0;
int lastRow = matrix.size() - 1;
int firstCol = 0;
int lastCol = matrix[0].size() - 1;
while(firstRow <= lastRow && firstCol <= lastCol){
for (int i = firstCol; i <= lastCol; i++){
result.push_back(matrix[firstRow][i]);
}
firstRow++;
if (firstCol <= lastCol){
for (int i = firstRow; i <= lastRow; i++){
result.push_back(matrix[i][lastCol]);
}
}
lastCol--;
if (firstRow <= lastRow){
for (int i = lastCol; i>= firstCol; i--) {
result.push_back(matrix[lastRow][i]);
}
lastRow--;
}
if (firstCol <= lastCol){
for (int i = lastRow; i >= firstRow; i--){
result.push_back(matrix[i][firstCol]);
}
firstCol++;
}
}
return result;
}
};