题目
按顺时针螺旋顺序访问矩阵中的全部元素,从左上角开始,返回访问序列。
示例输入
matrix = [[1,2,3],[4,5,6],[7,8,9]]示例输出
[1,2,3,6,9,8,7,4,5]思路
维护尚未访问区域的四条边界。依次访问上边、右边、下边、左边,每完成一条边就收缩相应边界。访问下边、左边前再次检查,避免单行或单列重复。
每一步都成立
四条边界之外的元素都已恰好访问一次,内部元素尚未访问。
看它一步步执行
用的是题目示例按平常的写法填:数组写 2 7 11 15 或 2, 7, 11, 15,矩阵每行一行,字符串不用加引号。也可以把力扣的示例整行粘贴进来,例如 nums = [2,7,11,15], target = 9。
核对结果(可选)
数组 / 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}
← → 单步 · 空格 播放
自己写一遍
只需实现下面的方法,输入输出由判题机处理。运行用下方的测试用例试一试;提交再用约 10 组隐藏用例检验。草稿自动保存在这个浏览器里。
还没有运行。写好代码后点“运行”。
ListNode、TreeNode、Node 已经定义好,可以直接使用;java.util 已默认导入。单组输入最多运行 4 秒,提交最多 6 秒。服务器同一时间只运行一份代码,人多时可能要排队几秒。