LeetCode: 54. Spiral Matrix(Medium)

时间:2023-01-21 14:31:32

1. 原题链接

https://leetcode.com/problems/spiral-matrix/description/

2. 题目要求

给定一个二维整型数组,返回其螺旋顺序列表,例如:

LeetCode: 54. Spiral Matrix(Medium)

最后返回结果为 [1,2,3,6,9,8,7,4,5]

3. 解题思路

按照螺旋的顺序进行遍历,每一次遍历螺旋顺序里的一个圈,如下图每一种颜色代表一次遍历得到的结果

LeetCode: 54. Spiral Matrix(Medium)

4. 代码实现

import java.util.ArrayList;
import java.util.List; public class SpiralMatrix54 {
public static void main(String[] args) {
int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {0, 0, 0}};
System.out.println(spiralOrder(matrix).toString());
} public static List<Integer> spiralOrder(int[][] matrix) {
List<Integer> res = new ArrayList<Integer>();
if (matrix.length == 0) return res;
int rowBegain = 0, rowEnd = matrix.length - 1; // 行数
int colBegain = 0, colEnd = matrix[0].length - 1; // 列数
while (rowBegain <= rowEnd && colBegain <= colEnd) { // 一次遍历一个螺旋顺序的圈
for (int i = colBegain; i <= colEnd; i++) {
res.add(matrix[rowBegain][i]);
}
rowBegain++; for (int i = rowBegain; i <= rowEnd; i++) {
res.add(matrix[i][colEnd]);
}
colEnd--; if (rowBegain <= rowEnd) {
for (int i = colEnd; i >= colBegain; i--)
res.add(matrix[rowEnd][i]);
}
rowEnd--; if (colBegain <= colEnd) {
for (int i = rowEnd; i >= rowBegain; i--)
res.add(matrix[i][colBegain]);
}
colBegain++;
} return res; }
}