Skip to main content
LeetCode 505, Medium. Topics: Depth-First Search, Breadth-First Search, Graph, Array, Matrix, Shortest Path, Dijkstra, Heap (Priority Queue). View on LeetCode. Generate this problem as a practice environment: tested reference solution, 12 parametrized pytest cases, and a playground notebook:

Problem

There is a ball in a maze with empty spaces (represented as 0) and walls (represented as 1). The ball can go through the 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 m x n maze, the ball’s start position and the destination, where start = [start_row, start_col] and destination = [destination_row, destination_col], return the shortest distance for the ball to stop at the destination. If the ball cannot stop at destination, return -1. The distance is the number of empty spaces traveled by the ball from the start position (excluded) to the destination (included). You may assume that the borders of the maze are all walls (see examples).

Examples

Example 1
Example 2

Constraints

  • m == maze.length
  • n == maze[i].length
  • 1 <= m, n <= 100
  • maze[i][j] is 0 or 1.
  • start.length == 2
  • destination.length == 2
  • 0 <= start_row, destination_row < m
  • 0 <= start_col, destination_col < n
  • Both the ball and the destination exist in an empty space, and they will not be in the same position initially.
  • The maze contains at least 2 empty spaces.

Solution

Reference implementation from solution.py on GitHub, full suite in test_solution.py:

Complexity

Tags

NeetCode All.
Last modified on September 7, 2026