Tags

,

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].
Key: note how we set the loop bound.

class Solution {
public:
vector<int> spiralOrder(vector<vector<int> > &matrix) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<int> result;
int rows = matrix.size();
if (rows == 0)
return result;
int cols = matrix[0].size();

for(int k=0;k<min(rows/2 + rows%2, cols/2 + cols%2); ++k)
{
for(int i=k; i<cols-k; ++i)
result.push_back(matrix[k][i]);
for(int i=k+1; i<rows-k; ++i)
result.push_back(matrix[i][cols-1-k]);
for(int i=k+1; i<cols-k && rows-1-k != k; ++i)
result.push_back(matrix[rows-1-k][cols-1-i]);
for(int i=k+1; i<rows-k-1 && k != cols-1-k; ++i)
result.push_back(matrix[rows-1-i][k]);
}

return result;
}
};
Advertisements