Given a matrix of m x n elements (m rows, n columns), return all elements of the Matri X 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]
.
Idea: Create functions to call each other recursively, the parameters of the function to include the direction
classSolution { Public: Vector<int> Spiralorder (vector<vector<int>> &matrix) { //Start Typing your/C + + solution below//Do not write int main () functionresult.clear (); if(Matrix.empty ())returnresult; LeftPos=0; Rightpos= matrix[0].size ()-1; Toppos=0; Bottompos= Matrix.size ()-1; Gowider (Matrix,true); returnresult; } voidGowider (vector<vector<int>> &matrix,BOOLDirect) { if(direct) { for(inti = LeftPos; I<= Rightpos; i++) {result.push_back (matrix[toppos][i]); } Toppos++; if(Toppos > Bottompos)return; Godeeper (Matrix,true); } Else { for(inti = Rightpos; I>= LeftPos; i--) {result.push_back (matrix[bottompos][i]); } Bottompos--; if(Toppos > Bottompos)return; Godeeper (Matrix,false); } } voidGodeeper (vector<vector<int>> &matrix,BOOLDirect) { if(direct) { for(inti = Toppos; I<= Bottompos; i++) {result.push_back (Matrix[i][rightpos]); } Rightpos--; if(LeftPos > Rightpos)return; Gowider (Matrix,false); } Else { for(inti = Bottompos; I>= Toppos; i--) {result.push_back (Matrix[i][leftpos]); } LeftPos++; if(LeftPos > Rightpos)return; Gowider (Matrix,true); } }Private: Vector<int>result; intLeftPos; intRightpos; intToppos; intBottompos;};
Spiral Matrix (Graph)