Problem

There is a ball in a maze with empty spaces and walls. The ball can go through empty spaces by rolling updownleft or rightbut 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.

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. 5.The maze contains at least 2 empty spaces, and both the width and height of the maze won’t exceed 100.

Examples

Example 1:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
Input:
map = 
[
 [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]
]
start = [0,4]
end = [3,2]
Output:
false

Example 2:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
Input:
map = 
[[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]
]
start = [0,4]
end = [4,4]
Output:
true

Solution

Method 1 – Depth-First Search (DFS) (1)

Intuition

The key idea is to use DFS to simulate the ball rolling in all four directions from the start position. The ball keeps rolling until it hits a wall, and we recursively check if the destination can be reached from the stopping point. We use a visited matrix to avoid cycles.

Approach

  1. Initialize a visited matrix to track visited positions.
  2. Start DFS from the start position.
  3. For each direction, roll the ball until it hits a wall.
  4. If the stopping position has not been visited, recursively call DFS from there.
  5. If the destination is reached, return true.
  6. If all paths are explored and the destination is not reached, return false.

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
    public boolean hasPath(int[][] maze, int[] start, int[] destination) {
        int m = maze.length, n = maze[0].length;
        boolean[][] vis = new boolean[m][n];
        return dfs(maze, start[0], start[1], destination, vis);
    }
    private boolean dfs(int[][] maze, int i, int j, int[] dest, boolean[][] vis) {
        if (vis[i][j]) return false;
        if (i == dest[0] && j == dest[1]) return true;
        vis[i][j] = true;
        int[][] dirs = {{0,1},{1,0},{0,-1},{-1,0}};
        for (int[] d : dirs) {
            int x = i, y = j;
            while (x+d[0] >= 0 && x+d[0] < maze.length && y+d[1] >= 0 && y+d[1] < maze[0].length && maze[x+d[0]][y+d[1]] == 0) {
                x += d[0]; y += d[1];
            }
            if (dfs(maze, x, y, dest, vis)) return true;
        }
        return false;
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution:
    def hasPath(self, maze: list[list[int]], start: list[int], destination: list[int]) -> bool:
        m, n = len(maze), len(maze[0])
        vis = [[False]*n for _ in range(m)]
        def dfs(i: int, j: int) -> bool:
            if vis[i][j]: return False
            if [i, j] == destination: return True
            vis[i][j] = True
            for dx, dy in ((0,1),(1,0),(0,-1),(-1,0)):
                x, y = i, j
                while 0 <= x+dx < m and 0 <= y+dy < n and maze[x+dx][y+dy] == 0:
                    x += dx; y += dy
                if dfs(x, y): return True
            return False
        return dfs(start[0], start[1])

Complexity

  • ⏰ Time complexity: O(mn), where m and n are the maze dimensions; each cell is visited at most once.
  • 🧺 Space complexity: O(mn), for the visited matrix and recursion stack.