LeetCode之爱的魔力转圈圈 54. Spiral Matrix

    xiaoxiao2022-07-04  115

    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] Example 2:

    Input: [ [1, 2, 3, 4], [5, 6, 7, 8], [9,10,11,12] ] Output: [1,2,3,4,8,12,11,10,9,5,6,7]

    没有更简便的方法,就是暴力解,O(m*n),方法就是四个变量x1,x2,y1,y2代表四个边界,每次走过一个方向就缩小一个边界,然后判断是否边界越界了:x1>x2或者y1>y2,如果符合则直接break,否则继续循环。
    public List<Integer> spiralOrder(int[][] matrix) { List<Integer> res = new ArrayList<>(); if (matrix.length == 0 || matrix[0].length == 0) return res; int x1 = 0; int x2 = matrix.length-1; int y1 = 0; int y2 = matrix[0].length-1; int x = 0; int y = 0; while (x1 <= x2 && y1 <= y2) { while (y <= y2) res.add(matrix[x][y++]); x1++; x++; y--; if (x1 > x2) break; while (x <= x2) res.add(matrix[x++][y]); y2--; x--; y--; if (y1 > y2) break; while (y >= y1) res.add(matrix[x][y--]); x2--; y++; x--; if (x1 > x2) break; while (x >= x1) res.add(matrix[x--][y]); y1++; x++; y++; } return res; }
    最新回复(0)