Problem description:
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
1 2 3 4 5 6 7 8 9 Example 1: Input: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] Output: [1,2,3,6,9,8,7,4,5]
1 2 3 4 5 6 7 8 9 Example 2: Input: [ [1, 2, 3, 4], [5, 6, 7, 8], [9,10,11,12] ] Output: [1,2,3,4,8,12,11,10,9,5,6,7]
Solution: This is a very simple and easy to understand solution. I traverse right and increment rowBegin, then traverse down and decrement colEnd, then I traverse left and decrement rowEnd, and finally I traverse up and increment colBegin.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 class Solution {public : vector <int > spiralOrder(vector <vector <int >>& matrix) { vector <int > res; if (matrix.size()== 0 ) return res; if (matrix[0 ].size()== 0 ) return res; int rowBegin = 0 ; int rowEnd = matrix.size()-1 ; int colBegin = 0 ; int colEnd = matrix[0 ].size() - 1 ; while (rowBegin <= rowEnd && colBegin <= colEnd) { for (int j = colBegin; j <= colEnd; j ++) { res.push_back(matrix[rowBegin][j]); } rowBegin++; for (int j = rowBegin; j <= rowEnd; j ++) { res.push_back(matrix[j][colEnd]); } colEnd--; if (rowBegin <= rowEnd) { for (int j = colEnd; j >= colBegin; j --) { res.push_back(matrix[rowEnd][j]); } } rowEnd--; if (colBegin <= colEnd) { for (int j = rowEnd; j >= rowBegin; j --) { res.push_back(matrix[j][colBegin]); } } colBegin ++; } return res; } };