目录
- 1.题目
- 2.答案
- 3.提交结果截图
链接: 54. 螺旋矩阵
1.题目
给你一个 m
行 n
列的矩阵 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]
提示:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 10
-100 <= matrix[i][j] <= 100
2.答案
class Solution {public List<Integer> spiralOrder(int[][] matrix) {// 遍历int size = matrix.length * matrix[0].length;List<Integer> list = new ArrayList<>(size);int circleIndex = 0;int i = 0;while (i < size) {int length = matrix[0].length - circleIndex * 2;for (int j = 0; j < length; j++) {int line = circleIndex;int column = circleIndex + j;list.add(matrix[line][column]);i++;}int width = matrix.length - 2 * circleIndex;if (width > 1) {for (int j = 1; j < width; j++) {int line = circleIndex + j;int column = circleIndex + length - 1;list.add(matrix[line][column]);i++;}if (length > 1) {for (int j = length - 2; j >= 0; j--) {int line = circleIndex + width - 1;int column = circleIndex + j;list.add(matrix[line][column]);i++;}for (int j = width - 2; j > 0; j--) {int line = circleIndex + j;int column = circleIndex;list.add(matrix[line][column]);i++;}}}circleIndex++;}return list;}
}
3.提交结果截图
整理完毕,完结撒花~ 🌻