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]
.
1 class Solution { 2 public: 3 vector<int> spiralOrder(vector<vector<int>>& matrix) { 4 vector<int> ans; 5 int xmin=0,ymin=0; 6 int xmax=matrix.size(); 7 if(!xmax) 8 return ans; 9 int ymax=matrix[0].size(); 10 11 int dir=1; 12 int count=0; 13 int cmax=xmax*ymax; 14 xmax--; 15 ymax--; 16 17 int x=0,y=0; 18 ans.push_back(matrix[x][y]); 19 count++; 20 21 while(count<cmax) 22 { 23 if(dir==1) 24 { 25 if(y+1>ymax) 26 { 27 dir=2; 28 xmin++; 29 } 30 else 31 { 32 y++; 33 ans.push_back(matrix[x][y]); 34 count++; 35 } 36 } 37 else if(dir==2) 38 { 39 if(x+1>xmax) 40 { 41 dir=3; 42 ymax--; 43 } 44 else 45 { 46 x++; 47 ans.push_back(matrix[x][y]); 48 count++; 49 } 50 } 51 else if(dir==3) 52 { 53 if(y-1<ymin) 54 { 55 dir=4; 56 xmax--; 57 } 58 else 59 { 60 y--; 61 ans.push_back(matrix[x][y]); 62 count++; 63 } 64 } 65 else 66 { 67 if(x-1<xmin) 68 { 69 dir=1; 70 ymin++; 71 } 72 else 73 { 74 x--; 75 ans.push_back(matrix[x][y]); 76 count++; 77 } 78 } 79 } 80 return ans; 81 } 82 };