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 List<Integer> spiralOrder(int[][] matrix) { List<Integer> result = new ArrayList<Integer>(); if( matrix.length == 0) return result; int left = 0,right = matrix[0].length-1; int num = matrix.length>matrix[0].length?matrix[0].length:matrix.length; num = num%2 == 0?num/2:num/2+1; for(int circle = 0 ;circle<num;circle++){ if( circle == matrix.length-circle-1){//只有一行 for( int i = left;i<=right;i++) result.add(matrix[circle][i]); return result; } if( left == right){//只有一列 for( int i = circle;i<matrix.length-circle;i++) result.add(matrix[i][right]); return result; } for( int i = left;i<=right;i++) result.add(matrix[circle][i]); for( int i = circle+1;i<matrix.length-circle;i++) result.add(matrix[i][right]); for( int i = right-1;i>=left;i--) result.add(matrix[matrix.length-circle-1][i]); for( int i = matrix.length-circle-2;i>circle;i--) result.add(matrix[i][left]); left++; right--; } return result; } }