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
| class Solution { public List<Integer> spiralOrder(int[][] matrix) { List<Integer> ans = new ArrayList<>(); int m = matrix.length; int n = matrix[0].length; circle(matrix, 0, 0, m - 1, n - 1, ans); return ans; } public void circle(int[][] mat, int x1, int y1, int x2, int y2,List<Integer> ans){ if(x1 > x2 || y1 > y2) return; if(x1 == x2){ for(int i = y1; i <= y2; i++) ans.add(mat[x1][i]); return; } if(y1 == y2){ for(int i = x1; i <= x2; i++) ans.add(mat[i][y1]);return; } for(int i = y1; i < y2; i++) ans.add(mat[x1][i]); for(int i = x1; i < x2; i++) ans.add(mat[i][y2]); for(int i = y2; i > y1; i--) ans.add(mat[x2][i]); for(int i = x2; i > x1; i--) ans.add(mat[i][y1]); circle(mat,x1 + 1, y1 + 1, x2 - 1, y2 - 1, ans); } }
|