矩阵

螺旋矩阵

中等#54Java时间 O(m n)空间 O(1),不含输出

题目要做什么

按顺时针螺旋顺序访问矩阵中的全部元素,从左上角开始,返回访问序列。

题目示例输入matrix = [[1,2,3],[4,5,6],[7,8,9]]
题目示例输出[1,2,3,6,9,8,7,4,5]

01 为什么这样做

维护尚未访问区域的四条边界。依次访问上边、右边、下边、左边,每完成一条边就收缩相应边界。访问下边、左边前再次检查,避免单行或单列重复。

始终成立的条件

四条边界之外的元素都已恰好访问一次,内部元素尚未访问。

02 看见算法执行

动画与代码同步

修改输入,播放自己的例子

当前使用题目示例
修改输入会改变执行过程;预期输出用于核对结果。
数组 / nums步骤 1
执行状态
本次演示输出播放到最后查看

Solution.java参考解法
1class Solution {2    public List<Integer> spiralOrder(int[][] matrix) {3        List<Integer> ans = new ArrayList<>();4        int top = 0, bottom = matrix.length - 1, left = 0, right = matrix[0].length - 1;5        while (top <= bottom && left <= right) {6            for (int c = left; c <= right; c++) ans.add(matrix[top][c]);7            top++;8            for (int r = top; r <= bottom; r++) ans.add(matrix[r][right]);9            right--;10            if (top <= bottom) {11                for (int c = right; c >= left; c--) ans.add(matrix[bottom][c]);12                bottom--;13            }14            if (left <= right) {15                for (int r = bottom; r >= top; r--) ans.add(matrix[r][left]);16                left++;17            }18        }19        return ans;20    }21}

键盘控制:A 后退 · D 前进

编程练习

↑↓ 选择↵ 打开Pagefind 全文检索