Spiral Matrix
1 class Solution { 2 public: 3 vector<int> spiralOrder(vector<vector<int> > &matrix) { 4 vector<int> res; 5 if (matrix.empty() || matrix[0].empty()) return res; 6 int imin = 0, imax = matrix.size()-1; 7 int jmin = 0, jmax = matrix[0].size()-1; 8 while (true) { 9 for (int j = jmin; j <= jmax; ++j) 10 res.push_back(matrix[imin][j]); 11 if (++imin > imax) break; 12 for (int i = imin; i <= imax; ++i) 13 res.push_back(matrix[i][jmax]); 14 if (jmin > --jmax) break; 15 for (int j = jmax; j >= jmin; --j) 16 res.push_back(matrix[imax][j]); 17 if (imin > --imax) break; 18 for (int i = imax; i >= imin; --i) 19 res.push_back(matrix[i][jmin]); 20 if (++jmin > jmax) break; 21 } 22 return res; 23 } 24 };
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].