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]
.
Hide TagsArray
Idea: DFS
Because the boundary condition is too many, the new array is constructed directly, the edges of which are int_min filled and the boundary is easily judged.
Take right for example, can right right, can't right down ... And so on
classSolution {enumDirect{right =0, down, left, up}; Vector<int>M_res; Public:#if1voidDfsintIintJenumDirect D, vector<vector<int> > &matrix) { if(Matrix[i][j]! = int_min)//This juge can deleted { //cout << i << ", \ T" << J << Endl;M_res.push_back (Matrix[i][j]); MATRIX[I][J]=int_min; if(d = =Right ) { if(matrix[i][j+1] !=int_min) Dfs (i, J+1, right, matrix); Else if(matrix[i+1][J]! =int_min) DFS (i+1, J, down, Matrix); } Else if(d = =Down ) { if(matrix[i+1][J]! =int_min) DFS (i+1, J, down, Matrix); Else if(matrix[i][j-1] !=int_min) Dfs (i, J-1, left, matrix); } Else if(d = =Left ) { if(matrix[i][j-1] !=int_min) Dfs (i, J-1, left, matrix); Else if(matrix[i-1][J]! =int_min) DFS (i-1, J, up, Matrix); } Else if(d = =Up ) { if(matrix[i-1][J]! =int_min) DFS (i-1, J, up, Matrix); Else if(matrix[i][j+1] !=int_min) Dfs (i, J+1, right, matrix); } } }#endifVector<int> Spiralorder (vector<vector<int> > &matrix) { if(matrix.size () = =0|| matrix[0].size () = =0) returnM_res; introw =matrix.size (); intCol = matrix[0].size (); Vector<vector<int> >Newmat; Vector<int> Intvec (col+2, int_min); Newmat.push_back (Intvec); for(inti =0; i < row; i++) { for(intj =0; J < Col; J + +) {intvec[j+1] =Matrix[i][j]; } newmat.push_back (Intvec); } intvec.clear (); Intvec.resize (Col+2, int_min); Newmat.push_back (Intvec); //for (int i = 0; i < newmat.size (); i++)//Printvector (Newmat[i]);DFS (1,1, Right,newmat); returnM_res; }};
[Leetcode] Spiral Matrix