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

二、题解
边界收缩法:四个边界
维护四个边界:
top = 0;
bottom = matrix.length - 1;
left = 0;
right = matrix[0].length - 1;
每一圈按照顺时针顺序遍历:
- 从左到右遍历上边
- 从上到下遍历右边
- 从右到左遍历下边
- 从下到上遍历左边
遍历完一条边,就把对应边界向内收缩。
注意:遍历下边和左边之前,要判断边界是否还合法,避免单行或单列时重复添加元素。
import java.util.*;
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;
int bottom = matrix.length - 1;
int left = 0;
int right = matrix[0].length - 1;
while (top <= bottom && left <= right) {
// 1. 从左到右
for (int col = left; col <= right; col++) {
result.add(matrix[top][col]);
}
top++;
// 2. 从上到下
for (int row = top; row <= bottom; row++) {
result.add(matrix[row][right]);
}
right--;
// 3. 从右到左
if (top <= bottom) {
for (int col = right; col >= left; col--) {
result.add(matrix[bottom][col]);
}
bottom--;
}
// 4. 从下到上
if (left <= right) {
for (int row = bottom; row >= top; row--) {
result.add(matrix[row][left]);
}
left++;
}
}
return result;
}
}
时间复杂度:
空间复杂度:
评论