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]
.
Subscribe to see which companies asked this question
1 public class Solution { 2 public List<Integer> spiralOrder(int[][] matrix) { 3 List<Integer> ans = new ArrayList<Integer>(); 4 if(matrix == null || matrix.length == 0 || matrix[0].length == 0) return ans; 5 int startx = 0,starty = 0,endx = matrix[0].length-1,endy = matrix.length-1; 6 7 while(startx <= endx && starty <= endy){ 8 for(int i = startx;i<=endx && starty <= endy;i++){// 该题这里需要判断下 starty endy 的边界,不然容易重复加入list 9 ans.add(matrix[starty][i]); 10 } 11 starty++; 12 13 for(int i = starty;i<=endy && startx <= endx;i++){ 14 ans.add(matrix[i][endx]); 15 } 16 endx--; 17 18 for(int i = endx;i>=startx && starty <= endy;i--){ 19 ans.add(matrix[endy][i]); 20 } 21 endy--; 22 23 for(int i = endy;i>=starty && startx <= endx;i--){ 24 ans.add(matrix[i][startx]); 25 } 26 startx++; 27 } 28 return ans; 29 } 30 }
对比59
Spiral Matrix II java solutions
http://www.cnblogs.com/guoguolan/p/5620000.html