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]
.
class Solution { public: vector<int> spiralOrder(vector<vector<int> > &matrix) { vector<int> result; if (matrix.size() == 0) { return result; } int left = 0; int top = 0; int bottom = matrix.size() - 1; int right = matrix[0].size() - 1; int row = 0; int column = 0; while (left <= right && top <= bottom) { if (column <= right) { while (column <= right) { result.push_back(matrix[row][column]); column++; } column--; top++; row++; } if (left <= right && top <= bottom && row <= bottom) { while (row <= bottom) { result.push_back(matrix[row][column]); row++; } row--; right--; column--; } if (left <= right && top <= bottom && column >= left) { while (column >= left) { result.push_back(matrix[row][column]); column--; } column++; bottom--; row--; } if (left <= right && top <= bottom && row >= top) { while (row >= top) { result.push_back(matrix[row][column]); row--; } row++; left++; column++; } } return result; } };