题目
给你一个 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
解题
方法一:模拟
思路
直接模拟,与【矩阵, 模拟】螺旋矩阵 II 差不多。
代码
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> ans = new ArrayList<>();
int m = matrix.length, n = matrix[0].length;
int beginX = 0, beginY = 0, boundX = m - 1, boundY = n - 1;
while (ans.size() < m * n) {
if (beginX <= boundX) {
for (int y = beginY; y <= boundY; ++y) ans.add(matrix[beginX][y]);
++beginX;
}
if (beginY <= boundY) {
for (int x = beginX; x <= boundX; ++x) ans.add(matrix[x][boundY]);
--boundY;
}
if (boundX >= beginX) {
for (int y = boundY; y >= beginY; --y) ans.add(matrix[boundX][y]);
--boundX;
}
if (boundY >= beginY) {
for (int x = boundX; x >= beginX; --x) ans.add(matrix[x][beginY]);
++beginY;
}
}
return ans;
}
}
评论区