Title: |
Spiral Matrix |
Pass Rate: |
20.8% |
Difficulty: |
Medium |
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]
.
First made the first version of the high pass rate, the given is 2Dmatrix, do this topic when I did not see clearly, directly in accordance with the 2Dmatrix, so there has been a problem.
It is important to note that the subject is m*n, so M and N may be empty, there may be a 1, then the cycle should be seriously considered.
Look directly at the code:
1 Public classSolution {2 PublicList<integer> Spiralorder (int[] matrix) {3Arraylist<integer> result=NewArraylist<integer>();4 if(Matrix = =NULL|| Matrix.length = = 05|| Matrix[0].length = = 0) {6 returnresult; 7 }8 intM=matrix.length,n=matrix[0].length;9 intStartx=0,starty=0,endx=m-1,endy=n-1;Ten while(startx<=endx&&starty<=EndY) { Oneresult=GetValue (Result,matrix,startx,endx,starty,endy); Astartx++; -starty++; -endx--; theendy--; - } - returnresult; - + } - PublicArraylist<integer> GetValue (arraylist<integer> res,int[] Matrix,intStartX,intEndX,intStarty,intEndY) { + if(startx==EndX) { A for(inti=starty;i<=endy;i++){ at Res.add (Matrix[startx][i]); - } - returnRes; - } - Else if(starty==EndY) { - for(inti=startx;i<=endx;i++){ in Res.add (Matrix[i][starty]); - } to returnRes; + } - the for(inti=starty;i<=endy;i++){ * Res.add (Matrix[startx][i]); $ }Panax Notoginseng for(inti=startx+1;i<=endx;i++){ - Res.add (Matrix[i][endy]); the } + for(inti=endy-1;i>=starty;i--){ A Res.add (Matrix[endx][i]); the } + for(inti=endx-1;i>=startx+1;i--){ - Res.add (Matrix[i][starty]); $ } $ returnRes; - - } the}
Leetcode------Spiral Matrix