KatInterview

490. The Maze

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks if a ball, starting at a specific position in a maze, can reach a destination. The ball's movement is unique: it rolls in a chosen direction (up, down, left, or right) until it hits a wall, at which point it stops. From this new stopping position, it can choose another direction to roll. The key condition is that the ball must stop at the destination, not just pass through it.

Solution

The Maze in Python

from collections import deque

class Solution:
    def hasPath(self, maze: List[List[int]], start: List[int], destination: List[int]) -> bool:
        m, n = len(maze), len(maze[0])
        
        # Queue for BFS, storing (row, col) of stopping points.
        queue = deque([tuple(start)])
        
        # visited_stops tracks stopping points we've already processed.
        visited_stops = {tuple(start)}

        # Directions for rolling: up, down, left, right.
        directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]

        while queue:
            r, c = queue.popleft()

            # If the current stopping point is the destination, we found a path.
            if r == destination[0] and c == destination[1]:
                return True

            # Explore all 4 directions from the current stopping point.
            for dr, dc in directions:
                nr, nc = r, c
                
                # Roll the ball in the current direction until it hits a wall.
                # The new position is the last empty space before the wall.
                while 0 <= nr + dr < m and 0 <= nc + dc < n and maze[nr + dr][nc + dc] == 0:
                    nr += dr
                    nc += dc
                
                # If this new stopping point (nr, nc) has not been visited yet.
                if (nr, nc) not in visited_stops:
                    visited_stops.add((nr, nc))
                    queue.append((nr, nc))

        # If the queue becomes empty and destination was not reached.
        return False

The Maze in Java

class Solution {
    public boolean hasPath(int[][] maze, int[] start, int[] destination) {
        int m = maze.length;
        int n = maze[0].length;

        // visited[r][c] = true means we have already started a roll from this stopping point.
        boolean[][] visited = new boolean[m][n];

        // Queue for BFS, storing {row, col} of stopping points.
        Queue<int[]> queue = new LinkedList<>();

        // Start BFS from the given start position.
        queue.offer(start);
        visited[start[0]][start[1]] = true;

        // Directions for rolling: up, down, left, right.
        int[][] dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};

        while (!queue.isEmpty()) {
            int[] curr = queue.poll();

            // If the current stopping point is the destination, we found a path.
            if (curr[0] == destination[0] && curr[1] == destination[1]) {
                return true;
            }

            // Explore all 4 directions from the current stopping point.
            for (int[] dir : dirs) {
                int r = curr[0];
                int c = curr[1];

                // Roll the ball in the current direction until it hits a wall.
                // The new position is the last empty space before the wall.
                while (r + dir[0] >= 0 && r + dir[0] < m && 
                       c + dir[1] >= 0 && c + dir[1] < n && 
                       maze[r + dir[0]][c + dir[1]] == 0) {
                    r += dir[0];
                    c += dir[1];
                }

                // If this new stopping point (r, c) has not been visited yet.
                if (!visited[r][c]) {
                    visited[r][c] = true;
                    queue.offer(new int[]{r, c});
                }
            }
        }

        // If the queue becomes empty and destination was not reached.
        return false;
    }
}

The Maze in C++

class Solution {
public:
    bool hasPath(vector<vector<int>>& maze, vector<int>& start, vector<int>& destination) {
        int m = maze.size();
        int n = maze[0].size();

        // visited[r][c] = true means we have already started a roll from this stopping point.
        vector<vector<bool>> visited(m, vector<bool>(n, false));

        // Queue for BFS, storing {row, col} of stopping points.
        queue<pair<int, int>> q;

        // Start BFS from the given start position.
        q.push({start[0], start[1]});
        visited[start[0]][start[1]] = true;

        // Directions for rolling: up, down, left, right.
        int dr[] = {-1, 1, 0, 0};
        int dc[] = {0, 0, -1, 1};

        while (!q.empty()) {
            pair<int, int> curr = q.front();
            q.pop();

            // If the current stopping point is the destination, we found a path.
            if (curr.first == destination[0] && curr.second == destination[1]) {
                return true;
            }

            // Explore all 4 directions from the current stopping point.
            for (int i = 0; i < 4; ++i) {
                int r = curr.first;
                int c = curr.second;

                // Roll the ball in the current direction until it hits a wall.
                // The new position is the last empty space before the wall.
                while (r + dr[i] >= 0 && r + dr[i] < m && 
                       c + dc[i] >= 0 && c + dc[i] < n && 
                       maze[r + dr[i]][c + dc[i]] == 0) {
                    r += dr[i];
                    c += dc[i];
                }

                // If this new stopping point (r, c) has not been visited yet.
                if (!visited[r][c]) {
                    visited[r][c] = true;
                    q.push({r, c});
                }
            }
        }

        // If the queue becomes empty and destination was not reached.
        return false;
    }
};

The Maze in TypeScript

function hasPath(maze: number[][], start: number[], destination: number[]): boolean {
    const m = maze.length;
    const n = maze[0].length;

    // visited[r][c] = true means we have already started a roll from this stopping point.
    const visited: boolean[][] = Array(m).fill(0).map(() => Array(n).fill(false));

    // Queue for BFS, storing [row, col] of stopping points.
    const queue: number[][] = [];

    // Start BFS from the given start position.
    queue.push(start);
    visited[start[0]][start[1]] = true;

    // Directions for rolling: up, down, left, right.
    const dirs = [[-1, 0], [1, 0], [0, -1], [0, 1]];

    while (queue.length > 0) {
        const curr = queue.shift()!;

        // If the current stopping point is the destination, we found a path.
        if (curr[0] === destination[0] && curr[1] === destination[1]) {
            return true;
        }

        // Explore all 4 directions from the current stopping point.
        for (const dir of dirs) {
            let r = curr[0];
            let c = curr[1];

            // Roll the ball in the current direction until it hits a wall.
            // The new position is the last empty space before the wall.
            while (
                r + dir[0] >= 0 && r + dir[0] < m &&
                c + dir[1] >= 0 && c + dir[1] < n &&
                maze[r + dir[0]][c + dir[1]] === 0
            ) {
                r += dir[0];
                c += dir[1];
            }

            // If this new stopping point (r, c) has not been visited yet.
            if (!visited[r][c]) {
                visited[r][c] = true;
                queue.push([r, c]);
            }
        }
    }

    // If the queue becomes empty and destination was not reached.
    return false;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.