54. 螺旋矩阵
查看题目中等
算法
高频
解法一:迭代法
时间复杂度:O(m×n) | 空间复杂度:O(m×n) | 推荐使用
动画演示
准备就绪 - 输入矩阵(行用分号分隔,列用逗号分隔),然后点击开始
代码实现
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> order = new ArrayList<Integer>();
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return order;
}
int rows = matrix.length, columns = matrix[0].length;
boolean[][] visited = new boolean[rows][columns];
int total = rows * columns;
int row = 0, column = 0;
int[][] directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
int directionIndex = 0;
for (int i = 0; i < total; i++) {
order.add(matrix[row][column]);
visited[row][column] = true;
int nextRow = row + directions[directionIndex][0], nextColumn = column + directions[directionIndex][1];
if (nextRow < 0 || nextRow >= rows || nextColumn < 0 || nextColumn >= columns || visited[nextRow][nextColumn]) {
directionIndex = (directionIndex + 1) % 4;
}
row += directions[directionIndex][0];
column += directions[directionIndex][1];
}
return order;
}
}时间复杂度:O(m×n)
空间复杂度:O(m×n)
**算法思路**:
1. 使用一个二维数组 visited 记录每个位置是否被访问过,
2. 使用四个方向的数组 directions 表示右、下、左、上四个方向
3. 从矩阵左上角开始,按照右→下→左→上的顺序循环遍历
4. 当遇到边界或已访问过的位置时,顺时针旋转方向
5. 直到访问完所有元素
**关键步骤**:
- 初始化访问矩阵和方向索引
- 遍历所有元素,每次访问一个元素后标记为已访问
- 检查下一个位置是否合法(未越界且未访问),否则切换方向
- 更新当前位置,继续遍历
**复杂度分析**:
- 时间复杂度:O(m×n),其中 m 和 n 分别是矩阵的行数和列数,每个元素只被访问一次
- 空间复杂度:O(m×n),主要用于存储访问状态和结果数组
**适用场景**:
- 需要按照螺旋顺序遍历二维矩阵的场景
- 适合各种大小的矩阵,包括空矩阵和非正方形矩阵
**注意事项**:
- 边界条件处理:空矩阵或单行/单列矩阵
- 方向切换的时机:当遇到边界或已访问元素时
- 访问状态的标记:确保每个元素只被访问一次