54.螺旋矩阵

2020/10/1

directions的数据顺序决定的了螺旋的顺序

class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> list = new ArrayList();
        int Y = matrix.length, X = matrix[0].length;
        
        boolean[][] visited = new boolean[Y][X];
        int[][] directions = {{0,1},{1,0},{0,-1},{-1,0}};

        int total = Y * X;
        int dirIndex = 0;
        int y=0, x=0;
        for(int i=0; i<total; i++){
            
            list.add(matrix[y][x]);
            visited[y][x] = true;
            int newY = y + directions[dirIndex][0], newX = x + directions[dirIndex][1];
            if(newY < 0 || newY > Y-1 || newX < 0 || newX > X-1 || visited[newY][newX]){ //这里是newY、newX而不是y、x
                dirIndex = (dirIndex+1)%4;
            }
            y =  y + directions[dirIndex][0];
            x =  x + directions[dirIndex][1];
        }

        return list;
    }
}

Last Updated: 4/4/2024