Spiral Matrix
https://leetcode.com/problems/spiral-matrix/description/
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
Solution 1
把遍历过的排除,即每次走完一行或一列,边界缩小。用rowBegin代表遍历起始行, rowEnd代表终点行, colBegin代表起始列, colEnd终点列。每遍历了一行, 就将相应begin和end指针往尚未遍历的方向移动。
Code
/*
* @lc app=leetcode id=54 lang=cpp
*
* [54] Spiral Matrix
*/
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
const int M = matrix.size(), N = M == 0 ? 0 : matrix[0].size();
vector<int> res;
int row_begin = 0, row_end = M - 1, col_begin = 0, col_end = N - 1;
while (row_begin <= row_end && col_begin <= col_end) {
for (int i = col_begin; i <= col_end; ++i) res.push_back(matrix[row_begin][i]);
++row_begin;
for (int i = row_begin; i <= row_end; ++i) res.push_back(matrix[i][col_end]);
--col_end;
if (row_begin > row_end) break;
for (int i = col_end; i >= col_begin; --i) res.push_back(matrix[row_end][i]);
--row_end;
if (col_begin > col_end) break;
for (int i = row_end; i >= row_begin; --i) res.push_back(matrix[i][col_begin]);
++col_begin;
}
return res;
}
};
Analysis
时间复杂度O(MN).
Solution 2
模拟走格的过程。当下一步会走出边界或重新走到已经访问过的时,变换方向。
Last updated
Was this helpful?