Title: Enter a matrix that prints each number in a clockwise order from the outside
Idea: Focus on 4 angles, according to which angle, in making the corresponding operation.
The code is as follows:
1 classSolution {2 Public:3vector<int> Printmatrix (vector<vector<int> >matrix) {4vector<int>results;5 if(matrix.size () = =0) {6 returnresults;7 }8 9 intx =0; Ten inty =0;//the position of the current element One A intXF =0; - intYF =1;//XF and YF represent the direction of the current element position pointer, -1 table back, 0 stop, 1 forward - the introws = Matrix.size ()-1;//Line - intcols = matrix.at (0). Size ()-1;//column - //when there is only one row - if(Rows = =0) { + for(inti =0; I <= cols; i++) { -Results.push_back (matrix.at (0). at (i)); + } A returnresults; at } - //When there is only one column - if(cols = =0) { - for(inti =0; I <= rows; i++) { -Results.push_back (matrix.at (i). at (0)); - } in returnresults; - } to + intX_start =0; - intY_start =0; the * intX_end =rows; $ intY_end =cols;Panax Notoginseng - BOOLIsFirst =true; the + intSize = (rows+1) * (cols+1);//Number of elements A while(Results.size () <size) { theResults.push_back (Matrix[x][y]);//Record Current element +x + = XF;//Horizontal Shift -Y + = YF;//Ordinate changes $ //start with four corner judgments and related operations $ if(x = = X_start && y = =y_end) { -XF =1; -YF =0; the if(!IsFirst) { -Y_start + =1;Wuyi } the } - if(x = = X_end && y = =y_end) { WuXF =0; -YF =-1; AboutY_end-=1; $ - - } - if(x = = X_end && y = =Y_start) { AXF =-1; +YF =0; theX_start + =1; - $ } the if(x = = X_start && y = =Y_start) { theXF =0; theYF =1; theX_end-=1; -IsFirst =false; in } the } the returnresults; About } the};
New Ket (1)