54. Spiral Matrix
2026/1/12大约 1 分钟约 347 字
54. Spiral Matrix
难度: Medium
题目描述
Given an m x n matrix, return all elements of the matrix in spiral order.
Example 1:

Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] Output: [1,2,3,6,9,8,7,4,5]
Example 2:

Input: matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]] Output: [1,2,3,4,8,12,11,10,9,5,6,7]
Constraints:
m == matrix.lengthn == matrix[i].length1 <= m, n <= 10-100 <= matrix[i][j] <= 100
解题思路
代码实现
解决方案
java
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
int row = matrix.length;
int col = matrix[0].length;
int[][] record = new int[row][col];
List<Integer> res = new ArrayList<>();
int mode = 0;
int rowIndex = 0;
int colIndex = 0;
int size = row * col;
while (res.size() < size) {
if (mode % 4 == 0) {
for (int i = colIndex; i < col && record[rowIndex][i] != 1; i++) {
res.add(matrix[rowIndex][i]);
record[rowIndex][i] = 1;
colIndex = i;
}
rowIndex++;
} else if (mode % 4 == 1) {
for (int i = rowIndex; i < row && record[i][colIndex] != 1; i++) {
res.add(matrix[i][colIndex]);
record[i][colIndex] = 1;
rowIndex=i;
}
colIndex--;
} else if (mode % 4 == 2) {
for (int i = colIndex; i > -1 && record[rowIndex][i] != 1; i--) {
res.add(matrix[rowIndex][i]);
record[rowIndex][i] = 1;
colIndex = i;
}
rowIndex--;
} else {
for (int i = rowIndex; i > -1 && record[i][colIndex] != 1; i--) {
res.add(matrix[i][colIndex]);
record[i][colIndex] = 1;
rowIndex=i;
}
colIndex++;
}
mode++;
}
return res;
}
}