Spiral Matrix
Solution 1
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
Solution 2
Last updated