LeetCode 54 Spiral Matrix

来源:互联网 发布:淘宝店家等级 编辑:程序博客网 时间:2024/04/28 08:21

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 List<Integer> spiralOrder(int[][] matrix) {   List<Integer> list = new ArrayList<Integer>();   int row = matrix.length - 1, column = row < 0 ? -1 : matrix[0].length - 1;   for (int x = 0, y = 0; x <= row && y <= column; x++, y++) {      //输出最外圈的第一行      for (int i = y; i <= column; i++) {         list.add(matrix[x][i]);      }      //输出最外圈的最右列      for (int i = x + 1; i <= row; i++) {         list.add(matrix[i][column]);      }      //输出最外圈的最底行,要注意防止和第一行重复      for (int i = column - 1; i >= y && x != row; i--) {         list.add(matrix[row][i]);      }      //输出最外圈的最左列,要注意防止和最右列重复      for (int i = row - 1; i > x && y != column; i--) {         list.add(matrix[i][y]);      }      row--;      column--;   }   return list;}

0 0
原创粉丝点击