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]
.
Subscribe to see which companies asked this question
1 Public classSolution {2 PublicList<integer> Spiralorder (int[] matrix) {3list<integer> ans =NewArraylist<integer>();4 if(Matrix = =NULL|| Matrix.length = = 0 | | Matrix[0].length = = 0)returnans;5 intStartX = 0,starty = 0,endx = Matrix[0].length-1,endy = Matrix.length-1;6 7 while(StartX <= endx && starty <=Endy) {8 for(inti = startx;i<=endx && starty <= endy;i++) {//The topic here needs to judge the boundary of Starty Endy, otherwise it is easy to re-join the list9 Ans.add (Matrix[starty][i]);Ten } Onestarty++; A - for(inti = Starty;i<=endy && startx <= endx;i++){ - Ans.add (Matrix[i][endx]); the } -endx--; - - for(inti = Endx;i>=startx && starty <= endy;i--){ + Ans.add (Matrix[endy][i]); - } +endy--; A at for(inti = Endy;i>=starty && startx <= endx;i--){ - Ans.add (Matrix[i][startx]); - } -startx++; - } - returnans; in } -}
Contrast 59
Spiral Matrix II Java Solutions
Http://www.cnblogs.com/guoguolan/p/5620000.html
Spiral Matrix Java Solutions