Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
Example 1:
Input:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
Output: [1,2,3,6,9,8,7,4,5]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/spiral-matrix
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
建四个边界,up,down,left,right,逆时针方向游走,把遍历到的元素一次加到list里面,当每一行或每一列遍历完时,边界自增或自减。
public List<Integer> spiralOrder(int[][] matrix) { List<Integer> list = new ArrayList<Integer>(); if(matrix == null || matrix.length == 0) { return list; } int up = 0; int d = matrix.length-1; int left = 0; int right = matrix[0].length-1; while(up<=d || left<=right) { //从左到右 for(int i = left; i <= right; i++) { list.add(matrix[up][i]); } up++; if(up > d) { break; } //从上到下 for(int i = up; i <= d; i++) { list.add(matrix[i][right]); } right--; if(left > right) { break; } //从右往左 for(int i = right; i >= left; i--) { list.add(matrix[d][i]); } d--; if(up > d) { break; } //从下往上 for(int i = d; i >= up; i--) { list.add(matrix[i][left]); } left++; if(left > right) { break; } } return list; }
运行效果如图: