发现横向和纵向在各自的方向上, 每轮走的步数–, 需要注意起点在(0, -1)
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 27 28 29 30 31
| class Solution {
public List<Integer> spiralOrder(int[][] matrix) { int m = matrix.length; int n = matrix[0].length; List<Integer> ans = new ArrayList<>(); int hor_step = n; int ver_step = m-1; int step = 1; int x = 0, y = -1; while (ans.size() < m * n) { for (int i = 0; i < hor_step; i++) { y += step; ans.add(matrix[x][y]); } for (int i = 0; i < ver_step; i++) { x += step; ans.add(matrix[x][y]); } hor_step--; ver_step--; step = -step; } return ans; } }
|