LeetCode 54. 螺旋矩阵-蛇皮走位

    技术2022-07-11  63

    给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。

    示例 1:

    输入: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] 输出: [1,2,3,6,9,8,7,4,5]

    示例 2:

    输入: [ [1, 2, 3, 4], [5, 6, 7, 8], [9,10,11,12] ] 输出: [1,2,3,4,8,12,11,10,9,5,6,7]

    我的做法就是暴力进行螺旋遍历,然后依次将数放进List集合里面。 所以我们需要一个标志位,判断当前位是否遍历过 还需要一个统计数。 遍历顺序:先向右,后向下,再向左,最后上 ( → ↓ ← ↑ ) 在遍历过程中注意边界条件!!

    class Solution { public List<Integer> spiralOrder(int[][] matrix) { List<Integer> res = new ArrayList<Integer>(); if(matrix == null || matrix.length == 0 || matrix[0].length == 0){ return res; } int row = matrix.length, col = matrix[0].length; int cnt = 1, r = 0, c = 0; // 标志位 int[][] flag = new int[row][col]; // 数组的第一位默认处理 flag[r][c] = 1; res.add(matrix[r][c]); // 遍历,需要注意边界条件 // 遍历时判断是否会越界并是否被访问过 while(cnt < row*col){ // 向右 while(c+1 < col && flag[r][c+1] == 0){ res.add(matrix[r][++c]); cnt++; flag[r][c] = 1; } // 向下 while(r+1 < row && flag[r+1][c] == 0){ res.add(matrix[++r][c]); cnt++; flag[r][c] = 1; } // 向左 while(c-1 >= 0 && flag[r][c-1] == 0){ res.add(matrix[r][--c]); cnt++; flag[r][c] = 1; } // 向上 while(r-1 >= 0 && flag[r-1][c] == 0){ res.add(matrix[--r][c]); cnt++; flag[r][c] = 1; } } return res; } }

    这解法简单粗暴,就是费时费空间

    Processed: 0.011, SQL: 9