螺旋矩阵
给你一个 m
行 n
列的矩阵 matrix
,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
示例 1:

1 2
| 输入:matrix = [[1,2,3],[4,5,6],[7,8,9]] 输出:[1,2,3,6,9,8,7,4,5]
|
示例 2:

1 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
定义两个数组模拟移动方向
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| class Solution { public List<Integer> spiralOrder(int[][] matrix) { int[] dx = new int[] { 0, 1, 0, -1 }; int[] dy = new int[] { 1, 0, -1, 0 }; List<Integer> list = new ArrayList<>(); int d = 0; int x = 0; int y = 0; int m = matrix.length; int n = matrix[0].length; for (int i = 0; i < m * n; i++) { list.add(matrix[x][y]); matrix[x][y] = 200; int nextX = x + dx[d]; int nextY = y + dy[d]; if (nextX < 0 || nextY < 0 || nextX >= m || nextY >= n || matrix[nextX][nextY] == 200) { d = (d + 1) % 4; nextX = x + dx[d]; nextY = y + dy[d]; } x = nextX; y = nextY; } return list; } }
|