数组与哈希中等1 种解法

#54螺旋矩阵

从左上角开始顺时针逐层返回矩阵中的所有元素。

#数组#矩阵#模拟

解题主线

01

维护尚未访问区域的上、右、下、左四条边,每走完一边立即收缩并检查是否越界。

解法 1四边界模拟

依次遍历上边、右边、下边、左边,每次遍历后收缩对应边界。

时间复杂度

O(mn)

空间复杂度

O(1),不计返回结果

54. 螺旋矩阵 · 四边界模拟
import java.util.ArrayList;
import java.util.List;

final class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> result = new ArrayList<>();
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return result;
        int top = 0, bottom = matrix.length - 1;
        int left = 0, right = matrix[0].length - 1;
        while (top <= bottom && left <= right) {
            for (int column = left; column <= right; column++) result.add(matrix[top][column]);
            if (++top > bottom) break;
            for (int row = top; row <= bottom; row++) result.add(matrix[row][right]);
            if (--right < left) break;
            for (int column = right; column >= left; column--) result.add(matrix[bottom][column]);
            if (--bottom < top) break;
            for (int row = bottom; row >= top; row--) result.add(matrix[row][left]);
            left++;
        }
        return result;
    }
}

依次遍历上边、右边、下边、左边,每次遍历后收缩对应边界。

  • 旧文件三个方法本质均为四边界模拟,合并为一个不重复访问的版本。

边界与易错点

  • 单行或单列矩阵在边界收缩后必须立即停止,否则会重复访问。
  • 矩阵为空时返回空列表;默认输入为规则矩形。
整理来源

由旧仓库源码复核、去重并整理;展示代码已按 Java 21 语义修正明显问题。

arr/Q054_螺旋矩阵.java