490. The Maze

87 阅读1分钟

image.png

image.png

方法

  • dfs,直到球碰到墙,再进行下一层的dfs
class Solution {
    public boolean hasPath(int[][] maze, int[] start, int[] destination) {
        boolean[][] visited = new boolean[maze.length][maze[0].length];
        return dfs(maze, start, destination, visited);
    }

    public boolean dfs(int[][] maze, int[] cur, int[] dest, boolean[][] visited) {
        if (visited[cur[0]][cur[1]]) {
            return false;
        }
        // ball 到达 dest
        if (cur[0] == dest[0] && cur[1] == dest[1]) {
            return true;
        }

        visited[cur[0]][cur[1]]= true;

        // dfs的四个方向
        int[] dirX = new int[]{0, 0, -1, 1}; // up, down, left, right
        int[] dirY = new int[]{-1, 1, 0, 0};

        // try 4 different directions
        for (int i = 0; i < 4; i++) {
            int row = cur[0], col = cur[1];
            // ball rolling until hit wall
            while (row >= 0 && row < maze.length 
                    && col >=0 && col < maze[0].length 
                    && maze[row][col] == 0) {
                row += dirY[i];
                col += dirX[i];
            }

            // ball hit wall, stop, dfs to find if cur pos can reach dest
            int[] next = new int[]{row - dirY[i], col - dirX[i]};
            if (dfs(maze, next, dest, visited)) {
                return true;
            }
        }
        return false;
    }
}