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
| class Solution { public List<Integer> spiralOrder(int[][] matrix) { List<Integer> ans = new ArrayList<>(); int m = matrix.length; int n = matrix[0].length; boolean[][] visit = new boolean[m][n]; int[][] direction = new int[][]{{0,1},{1,0},{0,-1},{-1,0}}; int total = m*n; int index = 0; int i = 0; int j = 0; for(int k = 0; k < total; k++){ ans.add(matrix[i][j]); visit[i][j] = true; int nextI = i + direction[index][0]; int nextJ = j + direction[index][1]; if(nextI<0||nextI>=m||nextJ<0||nextJ>=n||visit[nextI][nextJ]){ index = (index + 1)%4; } i = i + direction[index][0]; j = j + direction[index][1]; } return ans; } }
|