博客
关于我
leetcode题解54-螺旋矩阵
阅读量:798 次
发布时间:2023-01-31

本文共 2444 字,大约阅读时间需要 8 分钟。

为了给定矩阵按顺时针螺旋顺序遍历所有元素,可以使用边界变量控制逐层处理四个方向的移动。具体步骤如下:

  • 初始化边界变量left, right, top, bottom分别控制当前层的左、右、上、下。
  • 在每个循环层中,依次向右、向下、向左、向上移动,处理每个方向的元素。
  • 每个方向移动时,确保当前索引处的元素未被访问过,并标记为已访问,加入结果列表。
  • 在处理完四个方向后,收缩边界变量,进入下一层处理。
  • 当无法继续处理时,退出循环。
  • 以下是实现:

    class Solution {    public List
    spiralOrder(int[][] matrix) { List
    result = new ArrayList<>(); int m = matrix.length; if (m == 0) return result; int n = matrix[0].length; int[] visited = new int[m][n]; int left = 0, right = n - 1, top = 0, bottom = m - 1; int count = 0; while (left <= right && top <= bottom) { // Right pass for (int j = left; j <= right; j++) { if (count >= m * n) break; if (visited[top][j] == 0) { result.add(matrix[top][j]); visited[top][j] = 1; count++; } } top++; // Bottom pass for (int i = top; i <= bottom; i++) { if (count >= m * n) break; if (visited[i][right] == 0) { result.add(matrix[i][right]); visited[i][right] = 1; count++; } } right--; // Left pass if (top <= bottom) { for (int j = right; j >= left; j--) { if (count >= m * n) break; if (visited[bottom][j] == 0) { result.add(matrix[bottom][j]); visited[bottom][j] = 1; count++; } } bottom--; } // Up pass if (left <= right) { for (int i = bottom; i >= top; i--) { if (count >= m * n) break; if (visited[i][left] == 0) { result.add(matrix[i][left]); visited[i][left] = 1; count++; } } } } return result; }}

    逐步解释

  • 初始化边界:使用left, right, top, bottom变量来控制当前的遍历范围。
  • 右边界处理:从leftright处理每一行的元素,沿着右方向移动。对每个未访问的元素进行标记并加入结果。
  • 下边界处理:沿着下方向移动,从topbottom行的右边缘(right),对每个未访问的元素标记并加入结果。
  • 左边界处理:需要确保没有进入重复处理。此时,沿着左方向移动从rightleft,处理下一行(bottom)。
  • 上边界处理:沿着上方向移动,从bottomtop,处理左边缘(left)。
  • 收缩边界:在处理完四个方向后,收缩边界变量,移动到下一层处理。
  • 这种方法确保每一层被正确处理,并逐步收缩到矩阵的核心,避免重复访问任何元素,确保按照顺时针螺旋顺序遍历整个矩阵。

    转载地址:http://xegyk.baihongyu.com/

    你可能感兴趣的文章
    SQL-36 创建一个actor_name表,将actor表中的所有first_name以及last_name导入改表。
    查看>>
    ORM sqlachemy学习
    查看>>
    Ormlite数据库
    查看>>
    orm总结
    查看>>
    os.path.join、dirname、splitext、split、makedirs、getcwd、listdir、sep等的用法
    查看>>
    os.system 在 Python 中不起作用
    查看>>
    OSCACHE介绍
    查看>>
    SQL--合计函数(Aggregate functions):avg,count,first,last,max,min,sum
    查看>>
    OSChina 周五乱弹 ——吹牛扯淡的耽误你们学习进步了
    查看>>
    OSChina 周四乱弹 ——程序员为啥要买苹果手机啊?
    查看>>
    OSError: no library called “cairo-2“ was foundno library called “cairo“ was foundno library called
    查看>>
    Osgi环境配置
    查看>>
    OSG学习:几何体的操作(二)——交互事件、Delaunay三角网绘制
    查看>>
    OSG学习:几何对象的绘制(三)——几何元素的存储和几何体的绘制方法
    查看>>
    OSG学习:几何对象的绘制(二)——简易房屋
    查看>>
    OSG学习:场景图形管理(一)——视图与相机
    查看>>
    OSG学习:场景图形管理(三)——多视图相机渲染
    查看>>
    OSG学习:场景图形管理(二)——单窗口多相机渲染
    查看>>
    OSG学习:场景图形管理(四)——多视图多窗口渲染
    查看>>
    OSG学习:新建C++/CLI工程并读取模型(C++/CLI)——根据OSG官方示例代码初步理解其方法
    查看>>