> For the complete documentation index, see [llms.txt](https://protegejj.gitbook.io/algorithm-practice/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://protegejj.gitbook.io/algorithm-practice/leetcode/graph/490-the-maze.md).

# 490 The Maze

## 490. The Maze

## 1. Question

There is a **ball**in a maze with empty spaces and walls. The ball can go through empty spaces by rolling **up**,**down**,**left** or **right**, but it won't stop rolling until hitting a wall. When the ball stops, it could choose the next direction.

Given the ball's **start position**, the **destination**and the **maze**, determine whether the ball could stop at the destination.

The maze is represented by a binary 2D array. 1 means the wall and 0 means the empty space. You may assume that the borders of the maze are all walls. The start and destination coordinates are represented by row and column indexes.

**Example 1**

```
Input 1: a maze represented by a 2D array

0 0 1 0 0
0 0 0 0 0
0 0 0 1 0
1 1 0 1 1
0 0 0 0 0

Input 2: start coordinate (rowStart, colStart) = (0, 4)
Input 3: destination coordinate (rowDest, colDest) = (4, 4)

Output: true
Explanation: One possible way is : left -> down -> left -> down -> right -> down -> right.
```

![](/files/-LyrLEiznIThv-Tm8ch5)

**Example 2**

```
Input 1: a maze represented by a 2D array

0 0 1 0 0
0 0 0 0 0
0 0 0 1 0
1 1 0 1 1
0 0 0 0 0


Input 2: start coordinate (rowStart, colStart) = (0, 4)

Input 3: destination coordinate (rowDest, colDest) = (3, 2)


Output: false

Explanation: There is no way for the ball to stop at the destination.
```

![](/files/-LyrLEj0iHRevzb3GZzp)

**Note:**

1. There is only one ball and one destination in the maze.
2. Both the ball and the destination exist on an empty space, and they will not be at the same position initially.
3. The given maze does not contain border (like the red rectangle in the example pictures), but you could assume the border of the maze are all walls.
4. The maze contains at least 2 empty spaces, and both the width and height of the maze won't exceed 100.

## 2. Implementation

**(1) BFS**

```java
class Solution {
    public boolean hasPath(int[][] maze, int[] start, int[] destination) {
        if (maze == null || maze.length == 0 || maze[0].length == 0) {
            return false;
        }

        int m = maze.length, n = maze[0].length;
        boolean[][] visited = new boolean[m][n];

        Queue<int[]> queue = new LinkedList<>();
        queue.add(start);
        visited[start[0]][start[1]] = true;

        int[][] directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};

        while (!queue.isEmpty()) {
            int[] curCell = queue.remove();
            int curRow = curCell[0], curCol = curCell[1];

            if (curRow == destination[0] && curCol == destination[1]) {
                return true;
            }

            for (int[] direction : directions) {
                int nextRow = curRow + direction[0];
                int nextCol = curCol + direction[1];

                while (isValid(maze, nextRow, nextCol, visited)) {
                    nextRow += direction[0];
                    nextCol += direction[1];
                }
                nextRow -= direction[0];
                nextCol -= direction[1];

                if (!visited[nextRow][nextCol]) {
                    visited[nextRow][nextCol] = true;
                    queue.add(new int[] {nextRow, nextCol});
                }
            }
        }
        return false;
    }

    public boolean isValid(int[][] maze, int row, int col, boolean[][] visited) {
        return row >= 0 && row < maze.length && col >= 0 && col < maze[0].length && maze[row][col] == 0;
    }
}
```

**(1) DFS**

```java
public class Solution {
    public boolean hasPath(int[][] maze, int[] start, int[] destination) {
        if (maze == null || maze.length == 0 || maze[0].length == 0) {
            return false;
        }

        int m = maze.length, n = maze[0].length;
        boolean[][] visited = new boolean[m][n];
        int[][] directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};

        return searchPathByDFS(maze, start, destination, visited, directions);
    }

    public boolean searchPathByDFS(int[][] maze, int[] start, int[] destination, boolean[][] visited, int[][] directions) {
        int curRow = start[0];
        int curCol = start[1];

        if (visited[curRow][curCol]) {
            return false;
        }

        visited[curRow][curCol] = true;


        if (curRow == destination[0] && curCol == destination[1]) {
            return true;
        }

        for (int[] direction : directions) {
            int nextRow = curRow + direction[0];
            int nextCol = curCol + direction[1];

            while (isValid(nextRow, nextCol, maze)) {
                nextRow += direction[0];
                nextCol += direction[1];
            }
            nextRow -= direction[0];
            nextCol -= direction[1];

            if (searchPathByDFS(maze, new int[] {nextRow, nextCol}, destination, visited, directions)) {
                return true;
            }
        }
        return false;
    }

    public boolean isValid(int row, int col, int[][] maze) {
        return row >= 0 && row < maze.length && col >= 0 && col < maze[0].length && maze[row][col] == 0;
    }
}
```

## 3. Time & Space Complexity

**BFS**:时间复杂度O(mn), 空间复杂度Omn)

**DFS**:时间复杂度O(mn), 空间复杂度Omn)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://protegejj.gitbook.io/algorithm-practice/leetcode/graph/490-the-maze.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
