LeetCode-54. Spiral Matrix (JAVA)(顺时针打印矩阵)

来源:互联网 发布:淘宝返利网站哪个最好 编辑:程序博客网 时间:2024/06/18 00:31

54. Spiral Matrix

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].

解法1

public List<Integer> spiralOrder(int[][] arr) {List<Integer> res = new ArrayList<>();if (arr.length == 0)return res;int rows = arr.length;int cols = arr[0].length;// 此种方法关键点--求圈数// 最小值除以2,向上取整// int layers = (Math.min(rows, cols) - 1) / 2 + 1;int layers = (int) Math.ceil((Math.min(rows, cols)) / 2.0);// 要打印的圈数for (int i = 0; i < layers; i++) {// 打印每圈// 左至右for (int k = i; k < cols - i; k++)res.add(arr[i][k]);// 右上至右下for (int j = i + 1; j < rows - i; j++)res.add(arr[j][cols - i - 1]);// 注意k,j开始的下标// 右至左// (rows - i - 1 != i)避免重复打印第i行for (int k = cols - i - 2; (k >= i) && (rows - i - 1 != i); k--)res.add(arr[rows - i - 1][k]);// 左下至左上// (cols - i - 1 != i)避免重复打印第i列for (int j = rows - i - 2; (j > i) && (cols - i - 1 != i); j--)res.add(arr[j][i]);}return res;}

discuss解法

 The only tricky part is that when I traverse left or up I have to check whether the row or col still exists to prevent duplicates

(往左还是往上遍历 的时候,要检查是否row和col已经存在,避免重复打印(加入if判断))

public List<Integer> spiralOrder(int[][] matrix) {List<Integer> res = new ArrayList<Integer>();if (matrix.length == 0) {return res;}int up = 0;int down = matrix.length - 1;int left = 0;int right = matrix[0].length - 1;// 取到‘=’是因为走过的已经移动指针while (up <= down && left <= right) {// Traverse Right(→)for (int j = left; j <= right; j++) {res.add(matrix[up][j]);}up++;// Traverse Down(↓)for (int j = up; j <= down; j++) {res.add(matrix[j][right]);}right--;if (up <= down) {// Traverse Left(←)for (int j = right; j >= left; j--) {res.add(matrix[down][j]);}}down--;if (left <= right) {// Traver Up(↑)for (int j = down; j >= up; j--) {res.add(matrix[j][left]);}}left++;}return res;}

0 0
原创粉丝点击