public List<Integer> spiralOrder(int[][] matrix){ List<Integer> res = new ArrayList<>(); if(matrix == null || matrix.length == 0 || matrix[0].length == 0) return res; int[] dx = {0, 1, 0, -1}; //方向指引 int[] dy = {1, 0, -1, 0}; int x = 0, y = -1, t = 0; //t代表第几次方向,x,y初值是因为一开始往右走 boolean[][] isPass = newboolean[matrix.length][matrix[0].length]; for(int i = 0; i < matrix.length * matrix[0].length; i++){ if(!check(matrix, x + dx[t], y + dy[t], isPass)){ //转向 t = (t + 1) % 4; } x += dx[t]; y += dy[t]; res.add(matrix[x][y]); isPass[x][y] = true; } return res; }
publicbooleancheck(int[][] matrix, int x, int y, boolean[][] isPass){ return x >= 0 && x < matrix.length && y >= 0 && y < matrix[0].length && !isPass[x][y]; }