The Maze
The Maze is a medium graphs problem solved with the matrix graphs pattern.
The best approach, bfs over stopping cells, runs in O(m · n · (m + n)) time and O(m · n) space.
Below are 2 approaches in Java, Python, C++ and JavaScript, from dfs over stopping cells up.
Problem
A ball sits in a maze given as a grid of 0 (empty) and 1 (wall). Once pushed in one of the four directions (up, down, left, right), the ball keeps rolling until the next cell is a wall or lies outside the grid; only then does it stop and can be pushed again in any direction.
Given the start cell of the ball and a destination cell, return true if the ball can come to rest exactly on the destination, and false otherwise. Merely rolling over the destination does not count.
Examples
Example 1
- Input
maze = [[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], destination = [4,0]- Output
true- Why
- Roll left to (0,3), down to (1,3), left to (1,0), down to (2,0), right to (2,2), down to (4,2) and left to (4,0), where the border stops the ball.
Example 2
- Input
maze = [[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], destination = [4,1]- Output
false- Why
- The ball can roll across (4,1), but nothing ever stops it there: it always slides on to (4,0) or (4,2).
Constraints
1 <= m, n <= 100where the maze has m rows and n columns.- Every cell is
0(empty) or1(wall). startanddestinationare empty cells and are different.- The outer border behaves like a wall.
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (2 examples, or your own). Submit also runs 15 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| DFS over stopping cells | O(m · n · (m + n)) | O(m · n) |
| BFS over stopping cells | O(m · n · (m + n)) | O(m · n) |
1DFS over stopping cells
O(m · n · (m + n))Each of the m · n cells is expanded at most once, and each roll covers at most m + n cells.O(m · n)The visited matrix and the recursion stack.Recursively explore from the current stopping cell. For each direction, roll until blocked to find the next stopping cell and recurse into it if it has not been visited yet. Return true as soon as a stop lands on the destination.
- Mark the current cell visited; if it is the destination, return true.
- For each of the four directions, slide while the next cell is inside the grid and empty.
- If the cell where the ball stops is unvisited, recurse; propagate a true result.
- Return false when every direction is exhausted.
class Solution {
private final int[][] dirs = { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 } };
public boolean hasPath(int[][] maze, int[] start, int[] destination) {
boolean[][] seen = new boolean[maze.length][maze[0].length];
return dfs(maze, start[0], start[1], destination, seen);
}
private boolean dfs(int[][] maze, int r, int c, int[] dest, boolean[][] seen) {
if (seen[r][c]) return false;
seen[r][c] = true;
if (r == dest[0] && c == dest[1]) return true;
int m = maze.length, n = maze[0].length;
for (int[] d : dirs) {
int x = r, y = c;
while (x + d[0] >= 0 && x + d[0] < m && y + d[1] >= 0 && y + d[1] < n && maze[x + d[0]][y + d[1]] == 0) {
x += d[0];
y += d[1];
}
if (dfs(maze, x, y, dest, seen)) return true;
}
return false;
}
}class Solution:
def hasPath(self, maze: List[List[int]], start: List[int], destination: List[int]) -> bool:
m, n = len(maze), len(maze[0])
seen = [[False] * n for _ in range(m)]
dirs = [(1, 0), (-1, 0), (0, 1), (0, -1)]
def dfs(r: int, c: int) -> bool:
if seen[r][c]:
return False
seen[r][c] = True
if r == destination[0] and c == destination[1]:
return True
for dr, dc in dirs:
x, y = r, c
while 0 <= x + dr < m and 0 <= y + dc < n and maze[x + dr][y + dc] == 0:
x += dr
y += dc
if dfs(x, y):
return True
return False
return dfs(start[0], start[1])class Solution {
public:
bool hasPath(vector<vector<int>>& maze, vector<int>& start, vector<int>& destination) {
vector<vector<bool>> seen(maze.size(), vector<bool>(maze[0].size(), false));
return dfs(maze, start[0], start[1], destination, seen);
}
private:
int dirs[4][2] = { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 } };
bool dfs(vector<vector<int>>& maze, int r, int c, vector<int>& dest, vector<vector<bool>>& seen) {
if (seen[r][c]) return false;
seen[r][c] = true;
if (r == dest[0] && c == dest[1]) return true;
int m = maze.size(), n = maze[0].size();
for (auto& d : dirs) {
int x = r, y = c;
while (x + d[0] >= 0 && x + d[0] < m && y + d[1] >= 0 && y + d[1] < n && maze[x + d[0]][y + d[1]] == 0) {
x += d[0];
y += d[1];
}
if (dfs(maze, x, y, dest, seen)) return true;
}
return false;
}
};function hasPath(maze, start, destination) {
const m = maze.length, n = maze[0].length;
const seen = Array.from({ length: m }, () => new Array(n).fill(false));
const dirs = [[1, 0], [-1, 0], [0, 1], [0, -1]];
function dfs(r, c) {
if (seen[r][c]) return false;
seen[r][c] = true;
if (r === destination[0] && c === destination[1]) return true;
for (const d of dirs) {
let x = r, y = c;
while (x + d[0] >= 0 && x + d[0] < m && y + d[1] >= 0 && y + d[1] < n && maze[x + d[0]][y + d[1]] === 0) {
x += d[0];
y += d[1];
}
if (dfs(x, y)) return true;
}
return false;
}
return dfs(start[0], start[1]);
}2BFS over stopping cells
O(m · n · (m + n))Each cell is dequeued at most once and each of its four rolls costs at most m + n steps.O(m · n)The visited matrix and the queue.The same graph of stopping cells, explored level by level with a queue instead of recursion. This avoids deep recursion on large mazes and still visits each stopping cell once.
- Push the start into a queue and mark it visited.
- Pop a cell; if it is the destination, return true.
- For each direction, roll until the next cell is a wall or off the grid; enqueue the stopping cell if it is unvisited.
- If the queue empties, the destination is unreachable as a stop: return false.
class Solution {
public boolean hasPath(int[][] maze, int[] start, int[] destination) {
int m = maze.length, n = maze[0].length;
int[][] dirs = { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 } };
boolean[][] seen = new boolean[m][n];
Queue<int[]> q = new ArrayDeque<>();
q.add(new int[] { start[0], start[1] });
seen[start[0]][start[1]] = true;
while (!q.isEmpty()) {
int[] cur = q.poll();
if (cur[0] == destination[0] && cur[1] == destination[1]) return true;
for (int[] d : dirs) {
int x = cur[0], y = cur[1];
while (x + d[0] >= 0 && x + d[0] < m && y + d[1] >= 0 && y + d[1] < n && maze[x + d[0]][y + d[1]] == 0) {
x += d[0];
y += d[1];
}
if (!seen[x][y]) {
seen[x][y] = true;
q.add(new int[] { x, y });
}
}
}
return false;
}
}class Solution:
def hasPath(self, maze: List[List[int]], start: List[int], destination: List[int]) -> bool:
m, n = len(maze), len(maze[0])
dirs = [(1, 0), (-1, 0), (0, 1), (0, -1)]
seen = [[False] * n for _ in range(m)]
q = deque([(start[0], start[1])])
seen[start[0]][start[1]] = True
while q:
r, c = q.popleft()
if r == destination[0] and c == destination[1]:
return True
for dr, dc in dirs:
x, y = r, c
while 0 <= x + dr < m and 0 <= y + dc < n and maze[x + dr][y + dc] == 0:
x += dr
y += dc
if not seen[x][y]:
seen[x][y] = True
q.append((x, y))
return Falseclass Solution {
public:
bool hasPath(vector<vector<int>>& maze, vector<int>& start, vector<int>& destination) {
int m = maze.size(), n = maze[0].size();
int dirs[4][2] = { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 } };
vector<vector<bool>> seen(m, vector<bool>(n, false));
queue<pair<int, int>> q;
q.push({start[0], start[1]});
seen[start[0]][start[1]] = true;
while (!q.empty()) {
auto [r, c] = q.front();
q.pop();
if (r == destination[0] && c == destination[1]) return true;
for (auto& d : dirs) {
int x = r, y = c;
while (x + d[0] >= 0 && x + d[0] < m && y + d[1] >= 0 && y + d[1] < n && maze[x + d[0]][y + d[1]] == 0) {
x += d[0];
y += d[1];
}
if (!seen[x][y]) {
seen[x][y] = true;
q.push({x, y});
}
}
}
return false;
}
};function hasPath(maze, start, destination) {
const m = maze.length, n = maze[0].length;
const dirs = [[1, 0], [-1, 0], [0, 1], [0, -1]];
const seen = Array.from({ length: m }, () => new Array(n).fill(false));
const q = [[start[0], start[1]]];
seen[start[0]][start[1]] = true;
let head = 0;
while (head < q.length) {
const [r, c] = q[head++];
if (r === destination[0] && c === destination[1]) return true;
for (const d of dirs) {
let x = r, y = c;
while (x + d[0] >= 0 && x + d[0] < m && y + d[1] >= 0 && y + d[1] < n && maze[x + d[0]][y + d[1]] === 0) {
x += d[0];
y += d[1];
}
if (!seen[x][y]) {
seen[x][y] = true;
q.push([x, y]);
}
}
}
return false;
}Edge cases to test
- The ball rolls over the destination without stopping on it
- The start is boxed in on all four sides
- A single row or a single column
- Stopping points that form cycles (must not loop forever)
Hints
Hint 1
The ball only makes decisions at the cells where it stops. Treat those stopping cells as the nodes of a graph.
Hint 2
From a stopping cell, each of the four directions leads to exactly one next stopping cell: keep moving until the next cell is a wall or outside the grid.
Hint 3
Search this graph (BFS or DFS) from the start with a visited set, and check whether the destination is one of the reachable stopping cells.
FAQ
What is the best time complexity for The Maze?
BFS over stopping cells runs in O(m · n · (m + n)) time and O(m · n) extra space. Each cell is dequeued at most once and each of its four rolls costs at most m + n steps.
Which pattern does The Maze use?
It is a graphs problem that uses the matrix graphs pattern. Other problems with the same pattern: Flood Fill, Maximum Number of Points From Grid Queries, Contain Virus.
Is there a brute force solution for The Maze?
Yes. DFS over stopping cells takes O(m · n · (m + n)) time and O(m · n) space. Recursively explore from the current stopping cell.
Which edge cases should I test for The Maze?
The ball rolls over the destination without stopping on it; The start is boxed in on all four sides; A single row or a single column; Stopping points that form cycles (must not loop forever).