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 = [startrow, startcol] and destination = [destinationrow, destinationcol], 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.
The key insight is that the ball rolls until it hits a wall, making each stopping position a node in a graph. The optimal approach uses Dijkstra's algorithm with a priority queue to efficiently find the shortest path. Time: O(m×n×log(m×n)), Space: O(m×n)
Common Approaches
✓
BFS Level-by-Level
⏱️ Time: O(m×n×max(m,n))
Space: O(m×n)
Use a queue to explore positions in breadth-first order. Since we explore by levels, the first time we reach the destination gives us the shortest distance.
DFS with All Paths
⏱️ Time: O(4^(m×n))
Space: O(m×n)
Recursively explore all four directions from each position, rolling until hitting a wall. Track the minimum distance found to reach the destination.
Dijkstra with Priority Queue
⏱️ Time: O(m×n×log(m×n))
Space: O(m×n)
Use a priority queue (min-heap) to always process the position with minimum distance first. This ensures optimal path finding and avoids exploring unnecessary longer paths.
BFS Level-by-Level — Algorithm Steps
Start with initial position in queue
For each position, roll in all 4 directions
Add new positions to queue with updated distance
Return distance when destination is reached
Visualization
Tap to expand
Step-by-Step Walkthrough
1
Queue Start
Add starting position to queue
2
Level by Level
Process all positions at current distance
3
First Match
First time reaching destination gives shortest path
Code -
solution.c — C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#define MAX_SIZE 105
#define MAX_QUEUE 100000
typedef struct {
int x, y, dist;
} State;
int maze[MAX_SIZE][MAX_SIZE];
int dist[MAX_SIZE][MAX_SIZE];
int rows, cols;
int directions[4][2] = {{0,1},{1,0},{0,-1},{-1,0}};
// Queue
State queue[MAX_QUEUE];
int qFront, qRear;
void queueInit() { qFront = qRear = 0; }
void enqueue(int x, int y, int d) {
queue[qRear].x = x;
queue[qRear].y = y;
queue[qRear].dist = d;
qRear++;
}
State dequeue() { return queue[qFront++]; }
int queueEmpty() { return qFront == qRear; }
int solution(int sr, int sc, int dr, int dc) {
// Init dist array
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
dist[i][j] = INT_MAX;
dist[sr][sc] = 0;
queueInit();
enqueue(sr, sc, 0);
while (!queueEmpty()) {
State cur = dequeue();
int x = cur.x, y = cur.y, d = cur.dist;
// If we already found a shorter path, skip
if (d > dist[x][y]) continue;
// Try all 4 directions
for (int i = 0; i < 4; i++) {
int nx = x, ny = y, steps = 0;
// Roll until hitting a wall
while (nx + directions[i][0] >= 0 &&
nx + directions[i][0] < rows &&
ny + directions[i][1] >= 0 &&
ny + directions[i][1] < cols &&
maze[nx + directions[i][0]][ny + directions[i][1]] == 0) {
nx += directions[i][0];
ny += directions[i][1];
steps++;
}
int nd = d + steps;
// Only enqueue if we found a shorter distance
if (nd < dist[nx][ny]) {
dist[nx][ny] = nd;
enqueue(nx, ny, nd);
}
}
}
return dist[dr][dc] == INT_MAX ? -1 : dist[dr][dc];
}
void parseMaze(char* line) {
rows = 0; cols = 0;
int i = 0, len = strlen(line);
while (i < len && line[i] != '[') i++;
i++;
while (i < len) {
if (line[i] == '[') {
i++;
int c = 0;
while (i < len && line[i] != ']') {
if (line[i] >= '0' && line[i] <= '9') {
maze[rows][c++] = line[i] - '0';
}
i++;
}
if (rows == 0) cols = c;
rows++;
}
i++;
}
}
void parseArray(char* line, int* arr) {
int i = 0, len = strlen(line);
int idx = 0;
while (i < len) {
if (line[i] >= '0' && line[i] <= '9') {
int num = 0;
while (i < len && line[i] >= '0' && line[i] <= '9') {
num = num * 10 + (line[i] - '0');
i++;
}
arr[idx++] = num;
} else {
i++;
}
}
}
int main() {
char mazeLine[10000];
char startLine[100];
char destLine[100];
fgets(mazeLine, sizeof(mazeLine), stdin);
mazeLine[strcspn(mazeLine, "\n")] = '\0';
fgets(startLine, sizeof(startLine), stdin);
startLine[strcspn(startLine, "\n")] = '\0';
fgets(destLine, sizeof(destLine), stdin);
destLine[strcspn(destLine, "\n")] = '\0';
parseMaze(mazeLine);
int start[2], dest[2];
parseArray(startLine, start);
parseArray(destLine, dest);
int result = solution(start[0], start[1], dest[0], dest[1]);
printf("%d\n", result);
return 0;
}
Time & Space Complexity
Time Complexity
⏱️
O(m×n×max(m,n))
Each cell can be visited once, and rolling can take up to max(m,n) steps
n
2n
✓ Linear Growth
Space Complexity
O(m×n)
Queue can store up to m×n positions, plus visited array
n
2n
⚡ Linearithmic Space
142.0K Views
MediumFrequency
~25 minAvg. Time
1.9K Likes
Ln 1, Col 1
Smart Actions
💡Explanation
AI Ready
💡 SuggestionTabto acceptEscto dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen
Algorithm Visualization
Pinch to zoom • Tap outside to close
Test Cases
0 passed
0 failed
3 pending
Select Compiler
Choose a programming language
Compiler list would appear here...
AI Editor Features
Header Buttons
💡
Explain
Get a detailed explanation of your code. Select specific code or analyze the entire file. Understand algorithms, logic flow, and complexity.
🔧
Fix
Automatically detect and fix issues in your code. Finds bugs, syntax errors, and common mistakes. Shows you what was fixed.
💡
Suggest
Get improvement suggestions for your code. Best practices, performance tips, and code quality recommendations.
💬
Ask AI
Open an AI chat assistant to ask any coding questions. Have a conversation about your code, get help with debugging, or learn new concepts.
Smart Actions (Slash Commands)
🔧
/fix Enter
Find and fix issues in your code. Detects common problems and applies automatic fixes.
💡
/explain Enter
Get a detailed explanation of what your code does, including time/space complexity analysis.
🧪
/tests Enter
Automatically generate unit tests for your code. Creates comprehensive test cases.
📝
/docs Enter
Generate documentation for your code. Creates docstrings, JSDoc comments, and type hints.
⚡
/optimize Enter
Get performance optimization suggestions. Improve speed and reduce memory usage.
AI Code Completion (Copilot-style)
👻
Ghost Text Suggestions
As you type, AI suggests code completions shown in gray text. Works with keywords like def, for, if, etc.
Tabto acceptEscto dismiss
💬
Comment-to-Code
Write a comment describing what you want, and AI generates the code. Try: # two sum, # binary search, # fibonacci
💡
Pro Tip: Select specific code before using Explain, Fix, or Smart Actions to analyze only that portion. Otherwise, the entire file will be analyzed.