【java】54. 螺旋矩阵---注意四个边界值即可!!!
发布日期:2021-05-07 02:22:04 浏览次数:20 分类:精选文章

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

为了按顺时针螺旋顺序遍历矩阵中的所有元素,我们可以使用边界收缩的方法。具体步骤如下:

  • 初始化四个变量 topbottomleftright,分别表示当前遍历的矩阵的行的上界、下界、列的左界和右界。
  • 使用一个循环,逐层遍历矩阵,直到所有元素都被访问。
  • 在每一层循环中,按顺时针的顺序处理四个方向:右边、下面、左边和上面。
  • 处理完每一层后,收缩边界:上界增加1,右界减少1,下界减少1,左界增加1。
  • 重复上述步骤,直到所有元素都被访问。
  • 以下是实现代码:

    import java.util.ArrayList;import java.util.List;public class MatrixSpiralOrder {    public static List
    spiralOrder(int[][] matrix) { List
    result = new ArrayList<>(); int top = 0, bottom = matrix.length - 1; int left = 0, right = matrix[0].length - 1; while (top <= bottom && left <= right) { // 处理右边 for (int i = left; i <= right; i++) { result.add(matrix[top][i]); } top++; // 处理下面 for (int i = top; i <= bottom; i++) { result.add(matrix[i][right]); } right--; // 处理左边 if (left <= right) { for (int i = right; i >= left; i--) { result.add(matrix[bottom][i]); } bottom--; } // 处理上面 if (top <= bottom) { for (int i = bottom; i >= top; i--) { result.add(matrix[i][left]); } left++; } } return result; }}

    代码解释

  • 初始化变量topbottom 分别表示矩阵的行的上界和下界,leftright 分别表示列的左界和右界。
  • 循环处理:当 top 小于等于 bottomleft 小于等于 right 时,进入循环。
  • 处理右边:从 leftright,依次添加当前 top 行的元素。
  • 处理下面:从 topbottom,依次添加当前 right 列的元素。
  • 处理左边:如果 left 小于等于 right,则从 rightleft,依次添加当前 bottom 行的元素。
  • 处理上面:如果 top 小于等于 bottom,则从 bottomtop,依次添加当前 left 列的元素。
  • 收缩边界:更新 topbottomleftright,进入下一层循环。
  • 返回结果:当所有元素都被访问后,返回结果列表。
  • 这种方法确保了按顺时针螺旋顺序遍历矩阵中的所有元素,并且时间复杂度为 O(m*n),空间复杂度为 O(1)。

    上一篇:【java】59. 螺旋矩阵 II---快速学会if-elseif-else使用!!!
    下一篇:【java】706. 设计哈希映射---用定长数组表示MyHashMap!!!

    发表评论

    最新留言

    关注你微信了!
    [***.104.42.241]2025年04月03日 10时04分57秒