Spiral Matrix
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix 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]
.
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public class Solution { 2 public ArrayList<Integer> spiralOrder(int[][] matrix) { 3 int row = matrix.length; 4 ArrayList<Integer> res = new ArrayList<Integer> (); 5 if(row<=0) return res; 6 int col = matrix[0].length; 7 int start = 0; 8 while(start*2<row && start*2<col){ 9 print(matrix,start,res); 10 start++; 11 } 12 return res; 13 } 14 public void print(int[][] matrix,int start, ArrayList<Integer>res){ 15 int endX = matrix[0].length-1-start; 16 int endY = matrix.length-1-start; 17 18 //print up 19 for(int i=start;i<=endX;i++){ 20 res.add(matrix[start][i]); 21 } 22 //print right 23 for(int i=start+1;i<=endY;i++){ 24 res.add(matrix[i][endX]); 25 } 26 //print down 27 if(endY>start){ 28 for(int i=endX-1;i>=start;i--){ 29 res.add(matrix[endY][i]); 30 } 31 } 32 //print left 33 if(endX>start){ 34 for(int i=endY-1;i>start;i--){ 35 res.add(matrix[i][start]); 36 } 37 } 38 } 39 }
while(start*2<row && start*2<col)