【LeetCode 54】力扣算法:螺旋矩阵

题目:给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。

image


解这个算法的关键是操作四个边界:左边界、右边界、上边界和下边界。将边界的移动过程看作图上箭头的移动方向。随着我们按顺序访问矩阵中的元素,这些边界会逐渐向内移动。

核心思想:

通过循环,代码按照顺时针方向访问矩阵的边界元素,并将它们添加到结果列表中。

每次访问完一边后,相应的边界会向内移动,直到所有元素都被访问。

空间复杂度是 O (1) , 时间复杂度是 O ( m×n )

代码详细步骤:

  1. 初始化:首先,定义四个变量 top、bottom、left 和 right 分别表示当前处理的矩阵的上边界、下边界、左边界和右边界。创建一个空列表用于存储最终结果。

  2. 循环条件:在 top <= bottom 和 left <= right 的条件下进行循环。这个条件确保了还有未访问的元素。

  3. 访问上边界:从 left 到 right 遍历 top 行,将元素添加到 result 中。

  4. 移动边界:将 top 增加1,表示上边界下移一行。

  5. 访问右边界:从 top 到 bottom 遍历 right 列,将元素添加到 result 中。

  6. 移动边界:将 right 减少1,表示右边界左移一列。

  7. 检查是否继续:如果 top <= bottom,从 right 到 left 遍历 bottom 行,将元素添加到 result 中。

  8. 移动边界:将 bottom 减少1,表示下边界上移一行。

  9. 检查是否继续:如果 left <= right,从 bottom 到 top 遍历 left 列,将元素添加到 result 中。

  10. 移动边界:将 left 增加1,表示左边界右移一列。

  11. 返回结果:循环结束后,返回 result。

我的 Java 代码:

public class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> result = new ArrayList<>();
        if (matrix == null || matrix.length == 0) {
            return result;
        }

        int top = 0;                      //上边界初始为第0行
        int bottom = matrix.length - 1;   //下边界初始为最后一行
        int left = 0;                     //左边界初始为第0列
        int right = matrix[0].length - 1; //右边界初始为最后一列

        while (top <= bottom && left <= right) {
            // 1.访问上边界整行元素,最后把箭头转向
            for (int i = left; i <= right; i++) {
                result.add(matrix[top][i]);
            }
            top++;

            // 2.访问右边界整列(除开最上面那个元素),最后把箭头转向
            for (int i = top; i <= bottom; i++) {
                result.add(matrix[i][right]);
            }
            right--; 
            
            // 注意边界线不能互相越线
            if (top <= bottom) {  
                // 3.访问下边界整行元素,最后把箭头转向
                for (int i = right; i >= left; i--) {
                    result.add(matrix[bottom][i]);
                }
                bottom--;  
            }

            if (left <= right) {
                // 4.访问左边界整列(除开最底下的那个),最后把箭头转向
                for (int i = bottom; i >= top; i--) {
                    result.add(matrix[i][left]);
                }
                left++; 
            }
        }
        return result;
    }
}
posted @ 2025-07-25 01:16  junjunyi  阅读(37)  评论(0)    收藏  举报