KatInterview

505. The Maze II

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

This problem asks for the shortest distance for a ball to travel from a starting point to a destination in a maze. The ball's movement is unique: it rolls in a chosen direction (up, down, left, or right) until it hits a wall or the maze boundary. At this stopping point, it can choose a new direction.

Solution

The Maze II in Python

import heapq

class Solution:
    def shortestDistance(self, maze: list[list[int]], start: list[int], destination: list[int]) -> int:
        m, n = len(maze), len(maze[0])
        
        # distances[i][j] stores the shortest distance from start to (i, j)
        distances = [[float('inf')] * n for _ in range(m)]
        
        # Min-priority queue to store (distance, row, col)
        pq = [(0, start[0], start[1])]
        
        # Starting point
        distances[start[0]][start[1]] = 0
        
        # Directions for rolling: up, down, left, right
        dirs = [(-1, 0), (1, 0), (0, -1), (0, 1)]
        
        while pq:
            dist, r, c = heapq.heappop(pq)
            
            # If we've found a shorter path already, skip
            if dist > distances[r][c]:
                continue

            # Explore all four directions from the current stopping point (r, c)
            for dr, dc in dirs:
                new_r, new_c = r, c
                steps = 0
                
                # Roll the ball until it hits a wall or boundary
                while 0 <= new_r + dr < m and 0 <= new_c + dc < n and maze[new_r + dr][new_c + dc] == 0:
                    new_r += dr
                    new_c += dc
                    steps += 1
                
                # Check if we found a shorter path to the new stopping point
                if distances[r][c] + steps < distances[new_r][new_c]:
                    distances[new_r][new_c] = distances[r][c] + steps
                    heapq.heappush(pq, (distances[new_r][new_c], new_r, new_c))
        
        # Get the result for the destination
        result = distances[destination[0]][destination[1]]
        return result if result != float('inf') else -1

The Maze II in Java

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

        // distances[i][j] stores the shortest distance from start to (i, j)
        int[][] distances = new int[m][n];
        for (int[] row : distances) {
            Arrays.fill(row, Integer.MAX_VALUE);
        }

        // Min-priority queue to store {distance, row, col}
        // Lambda expression for comparing arrays based on distance
        PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[0] - b[0]);

        // Starting point
        distances[start[0]][start[1]] = 0;
        pq.offer(new int[]{0, start[0], start[1]});

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

        while (!pq.isEmpty()) {
            int[] current = pq.poll();
            int dist = current[0];
            int r = current[1];
            int c = current[2];

            // If we've found a shorter path already, skip
            if (dist > distances[r][c]) {
                continue;
            }

            // Explore all four directions from the current stopping point (r, c)
            for (int[] dir : dirs) {
                int dr = dir[0];
                int dc = dir[1];
                int newR = r;
                int newC = c;
                int steps = 0;

                // Roll the ball until it hits a wall or boundary
                while (newR + dr >= 0 && newR + dr < m && newC + dc >= 0 && newC + dc < n && maze[newR + dr][newC + dc] == 0) {
                    newR += dr;
                    newC += dc;
                    steps++;
                }

                // Check if we found a shorter path to the new stopping point
                if (distances[r][c] + steps < distances[newR][newC]) {
                    distances[newR][newC] = distances[r][c] + steps;
                    pq.offer(new int[]{distances[newR][newC], newR, newC});
                }
            }
        }

        // Get the result for the destination
        int result = distances[destination[0]][destination[1]];
        return result == Integer.MAX_VALUE ? -1 : result;
    }
}

The Maze II in C++

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

        // distances[i][j] stores the shortest distance from start to (i, j)
        vector<vector<int>> distances(m, vector<int>(n, INT_MAX));

        // Min-priority queue to store {distance, row, col}
        priority_queue<tuple<int, int, int>, vector<tuple<int, int, int>>, greater<tuple<int, int, int>>> pq;

        // Starting point
        distances[start[0]][start[1]] = 0;
        pq.push({0, start[0], start[1]});

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

        while (!pq.empty()) {
            auto [dist, r, c] = pq.top();
            pq.pop();

            // If we've found a shorter path already, skip
            if (dist > distances[r][c]) {
                continue;
            }
            
            // Explore all four directions from the current stopping point (r, c)
            for (auto& dir : dirs) {
                int dr = dir[0];
                int dc = dir[1];
                int new_r = r;
                int new_c = c;
                int steps = 0;

                // Roll the ball until it hits a wall or boundary
                while (new_r + dr >= 0 && new_r + dr < m && new_c + dc >= 0 && new_c + dc < n && maze[new_r + dr][new_c + dc] == 0) {
                    new_r += dr;
                    new_c += dc;
                    steps++;
                }

                // Check if we found a shorter path to the new stopping point
                if (distances[r][c] + steps < distances[new_r][new_c]) {
                    distances[new_r][new_c] = distances[r][c] + steps;
                    pq.push({distances[new_r][new_c], new_r, new_c});
                }
            }
        }

        // Get the result for the destination
        int result = distances[destination[0]][destination[1]];
        return result == INT_MAX ? -1 : result;
    }
};

The Maze II in TypeScript

type PQElement = [number, number, number]; // [distance, row, col]

class MinPriorityQueue {
    private heap: PQElement[] = [];

    private parent(i: number): number { return Math.floor((i - 1) / 2); }
    private left(i: number): number { return 2 * i + 1; }
    private right(i: number): number { return 2 * i + 2; }
    private swap(i: number, j: number): void {
        [this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]];
    }

    push(item: PQElement): void {
        this.heap.push(item);
        let i = this.heap.length - 1;
        while (i > 0 && this.heap[this.parent(i)][0] > this.heap[i][0]) {
            this.swap(i, this.parent(i));
            i = this.parent(i);
        }
    }

    pop(): PQElement | undefined {
        if (this.heap.length === 0) return undefined;
        this.swap(0, this.heap.length - 1);
        const item = this.heap.pop();
        this.heapify(0);
        return item;
    }

    private heapify(i: number): void {
        const l = this.left(i);
        const r = this.right(i);
        let smallest = i;
        if (l < this.heap.length && this.heap[l][0] < this.heap[smallest][0]) {
            smallest = l;
        }
        if (r < this.heap.length && this.heap[r][0] < this.heap[smallest][0]) {
            smallest = r;
        }
        if (smallest !== i) {
            this.swap(i, smallest);
            this.heapify(smallest);
        }
    }
    
    isEmpty(): boolean {
        return this.heap.length === 0;
    }
}

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

    // distances[i][j] stores the shortest distance from start to (i, j)
    const distances: number[][] = Array(m).fill(0).map(() => Array(n).fill(Infinity));

    // Min-priority queue to store [distance, row, col]
    const pq = new MinPriorityQueue();

    // Starting point
    distances[start[0]][start[1]] = 0;
    pq.push([0, start[0], start[1]]);

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

    while (!pq.isEmpty()) {
        const [dist, r, c] = pq.pop()!;

        // If we've found a shorter path already, skip
        if (dist > distances[r][c]) {
            continue;
        }

        // Explore all four directions from the current stopping point (r, c)
        for (const [dr, dc] of dirs) {
            let newR = r;
            let newC = c;
            let steps = 0;

            // Roll the ball until it hits a wall or boundary
            while (newR + dr >= 0 && newR + dr < m && newC + dc >= 0 && newC + dc < n && maze[newR + dr][newC + dc] === 0) {
                newR += dr;
                newC += dc;
                steps++;
            }

            // Check if we found a shorter path to the new stopping point
            if (distances[r][c] + steps < distances[newR][newC]) {
                distances[newR][newC] = distances[r][c] + steps;
                pq.push([distances[newR][newC], newR, newC]);
            }
        }
    }

    // Get the result for the destination
    const result = distances[destination[0]][destination[1]];
    return result === Infinity ? -1 : result;
}

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.