Algorithm/src/main/java/matrix/SpiralOrder.java
2025-03-13 18:56:26 +08:00

67 lines
2.4 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package matrix;
import java.util.ArrayList;
import java.util.List;
/**
* 题目54. 螺旋矩阵 (spiralOrder)
* 描述:给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
* 链接https://leetcode.cn/problems/spiral-matrix/
示例 1:
输入matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]
示例 2:
输入matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
输出:[1,2,3,4,8,12,11,10,9,5,6,7]
*/
//没想出
public class SpiralOrder {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> result = new ArrayList<>();
// 边界判断:空矩阵直接返回空结果
if (matrix == null || matrix.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 j = left; j <= right; j++) {
result.add(matrix[top][j]);
}
top++; // 遍历完上边界后,上边界下移
// 2. 从上到下遍历右边界
for (int i = top; i <= bottom; i++) {
result.add(matrix[i][right]);
}
right--; // 遍历完右边界后,右边界左移
// 3. 判断是否还有剩余的行,若有,则从右到左遍历下边界
if (top <= bottom) {
for (int j = right; j >= left; j--) {
result.add(matrix[bottom][j]);
}
bottom--; // 遍历完下边界后,下边界上移
}
// 4. 判断是否还有剩余的列,若有,则从下到上遍历左边界
if (left <= right) {
for (int i = bottom; i >= top; i--) {
result.add(matrix[i][left]);
}
left++; // 遍历完左边界后,左边界右移
}
}
return result;
}
}