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]
.
public class Solution { public ArrayList<Integer> spiralOrder(int[][] matrix) { ArrayList<Integer> result = new ArrayList<Integer>(); int rows = matrix.length; if(rows == 0){ return result; } int cols = matrix[0].length; if(cols == 0) return result; int start = 0; while(rows > start * 2 && cols > start * 2){ printCircle(matrix, rows, cols, start, result); start ++; } return result; } public void printCircle(int[][] matrix, int rows, int cols, int start, ArrayList<Integer> result){ int endX = cols - 1 - start; int endY = rows - 1 - start; // print up for(int i = start; i <= endX; i++){ result.add(matrix[start][i]); } // print right if(endY > start){ for(int i = start + 1; i <= endY; i ++){ result.add(matrix[i][endX]); } } // print down if(endX > start && endY > start){ for(int i = endX - 1; i >= start; i--){ result.add(matrix[endY][i]); } } // print left 转到最左边的时候 高度又减少了1,因为被下面的那一行多占了1 if(endX > start && endY - 1 > start){ for(int i = endY - 1; i > start; i--){ result.add(matrix[i][start]); } } } }
原文:http://www.cnblogs.com/RazerLu/p/3544280.html