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]
.
相当于一圈一圈的剥掉矩阵,剥掉一圈,row-2, col-2
1 public class Solution { 2 public ArrayList<Integer> spiralOrder(int[][] matrix) { 3 ArrayList<Integer> result = new ArrayList<Integer>(); 4 int rows = matrix.length; 5 if(rows == 0){ 6 return result; 7 } 8 int cols = matrix[0].length; 9 if(cols == 0) 10 return result; 11 12 int start = 0; 13 // 相当于一圈一圈的剥掉矩阵,剥掉一圈,row-2, col-2 14 while(rows > start * 2 && cols > start * 2){ 15 printCircle(matrix, rows, cols, start, result); 16 start ++; 17 } 18 return result; 19 } 20 21 public void printCircle(int[][] matrix, int rows, int cols, int start, ArrayList<Integer> result){ 22 int endX = cols - 1 - start; 23 int endY = rows - 1 - start; 24 25 // print up 26 for(int i = start; i <= endX; i++){ 27 result.add(matrix[start][i]); 28 } 29 30 // print right 31 if(endY > start){ 32 for(int i = start + 1; i <= endY; i ++){ 33 result.add(matrix[i][endX]); 34 } 35 } 36 // print down 37 if(endX > start && endY > start){ 38 for(int i = endX - 1; i >= start; i--){ 39 result.add(matrix[endY][i]); 40 } 41 } 42 // print left 转到最左边的时候 高度又减少了1,因为被下面的那一行多占了1 43 if(endX > start && endY - 1 > start){ 44 for(int i = endY - 1; i > start; i--){ 45 result.add(matrix[i][start]); 46 } 47 } 48 } 49 }