Java matrix runtime error

前端 未结 2 465
夕颜
夕颜 2021-01-29 09:34

Exercise letter:

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

For example, Given the

2条回答
  •  情书的邮戳
    2021-01-29 09:53

    Try this.

    static int[][] DIRECTIONS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
    
    static boolean movable(int r, int c, int height, int width, boolean[][] visited) {
        if (r < 0 || r >= height || c < 0 || c >= width)
            return false;
        return !visited[r][c];
    }
    
    public List spiralOrder(int[][] matrix) {
        List result = new ArrayList<>();
        int height = matrix.length;
        if (height == 0) return result;
        int width = matrix[0].length;
        if (width == 0) return result;
        boolean[][] visited = new boolean[height][width];
        int direction = 0;
        int r = 0, c = 0;
        for (int i = 0; i < width * height; ++i) {
            result.add(matrix[r][c]);
            visited[r][c] = true;
            int[] directions = DIRECTIONS[direction % DIRECTIONS.length];
            if (!movable(r + directions[0], c + directions[1], height, width, visited))
                directions = DIRECTIONS[++direction % DIRECTIONS.length];
            r += directions[0];
            c += directions[1];
        }
        return result;
    }
    

提交回复
热议问题