Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
For example,
Given the following matrix:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
You should return [1,2,3,6,9,8,7,4,5]
.
Code:
<span style="font-size:14px;">class Solution {
public:
vector<int> spiralOrder(vector<vector<int> > &matrix) {
vector<int> result;
const int m = matrix.size();
if (m == 0) return result;
const int n = matrix[0].size();
for (int i = 0; i <= (min(m, n)-1)/2; ++i) {
for (int j = i; j <= n-1-i; ++j)
result.push_back(matrix[i][j]);
for (int j = i+1; j <= m-2-i; ++j)
result.push_back(matrix[j][n-1-i]);
if (i >= m-1-i) break;
for (int j = n-1-i; j >= i; --j)
result.push_back(matrix[m-1-i][j]);
if (i >= n-1-i) break;
for (int j = m-2-i; j >= i+1; --j)
result.push_back(matrix[j][i]);
}
return result;
}
};</span>