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 <ctype.h>
typedef struct {
int dist, x, y;
} HeapNode;
typedef struct {
HeapNode* data;
int size;
int capacity;
} MinHeap;
static int distances[100][100];
static int maze_data[100][100];
MinHeap* createHeap(int capacity) {
MinHeap* heap = malloc(sizeof(MinHeap));
heap->data = malloc(capacity * sizeof(HeapNode));
heap->size = 0;
heap->capacity = capacity;
return heap;
}
void swap(HeapNode* a, HeapNode* b) {
HeapNode temp = *a;
*a = *b;
*b = temp;
}
void heapifyUp(MinHeap* heap, int idx) {
if (idx && heap->data[idx].dist < heap->data[(idx - 1) / 2].dist) {
swap(&heap->data[idx], &heap->data[(idx - 1) / 2]);
heapifyUp(heap, (idx - 1) / 2);
}
}
void heapifyDown(MinHeap* heap, int idx) {
int smallest = idx;
int left = 2 * idx + 1;
int right = 2 * idx + 2;
if (left < heap->size && heap->data[left].dist < heap->data[smallest].dist)
smallest = left;
if (right < heap->size && heap->data[right].dist < heap->data[smallest].dist)
smallest = right;
if (smallest != idx) {
swap(&heap->data[idx], &heap->data[smallest]);
heapifyDown(heap, smallest);
}
}
void heapPush(MinHeap* heap, HeapNode node) {
heap->data[heap->size] = node;
heapifyUp(heap, heap->size);
heap->size++;
}
HeapNode heapPop(MinHeap* heap) {
HeapNode root = heap->data[0];
heap->data[0] = heap->data[heap->size - 1];
heap->size--;
heapifyDown(heap, 0);
return root;
}
int solution(int** maze, int m, int n, int* start, int* destination) {
int directions[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
// Initialize distances array with -1 (unvisited)
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
distances[i][j] = -1;
}
}
MinHeap* heap = createHeap(10000);
HeapNode start_node = {0, start[0], start[1]};
heapPush(heap, start_node);
while (heap->size > 0) {
HeapNode curr = heapPop(heap);
int dist = curr.dist, x = curr.x, y = curr.y;
if (x == destination[0] && y == destination[1]) {
free(heap->data);
free(heap);
return dist;
}
// Skip if already processed with better or equal distance
if (distances[x][y] != -1) {
continue;
}
distances[x][y] = dist;
for (int i = 0; i < 4; i++) {
int dx = directions[i][0], dy = directions[i][1];
int nx = x, ny = y;
int steps = 0;
// Roll until hitting wall
while (0 <= nx + dx && nx + dx < m && 0 <= ny + dy && ny + dy < n && maze[nx + dx][ny + dy] == 0) {
nx += dx;
ny += dy;
steps++;
}
if (steps > 0 && distances[nx][ny] == -1) {
HeapNode new_node = {dist + steps, nx, ny};
heapPush(heap, new_node);
}
}
}
free(heap->data);
free(heap);
return -1;
}
void parseArray(const char* str, int* arr, int* size) {
*size = 0;
const char* p = str;
while (*p && *p != '[') p++;
if (*p == '[') p++;
while (*p && *p != ']') {
while (*p && (*p == ' ' || *p == ',' || *p == '\n' || *p == '\r')) p++;
if (*p == ']' || *p == '\0') break;
if (isdigit(*p) || *p == '-') {
arr[(*size)++] = (int)strtol(p, (char**)&p, 10);
} else {
p++;
}
}
}
int parseMatrix(const char* str, int maze[100][100], int* cols) {
int rows = 0;
*cols = 0;
const char* p = str;
// Skip to first opening bracket
while (*p && *p != '[') p++;
if (*p == '[') p++;
while (*p) {
// Skip whitespace and commas
while (*p && (*p == ' ' || *p == ',' || *p == '\n' || *p == '\r')) p++;
if (*p == '[') {
// Found start of a row
p++; // Skip opening bracket
int col = 0;
while (*p && *p != ']') {
// Skip whitespace and commas
while (*p && (*p == ' ' || *p == ',' || *p == '\n' || *p == '\r')) p++;
if (*p == ']') break;
if (isdigit(*p) || *p == '-') {
maze[rows][col++] = (int)strtol(p, (char**)&p, 10);
} else {
p++;
}
}
if (*p == ']') p++; // Skip closing bracket of row
if (rows == 0) *cols = col; // Set column count from first row
rows++;
} else if (*p == ']') {
// End of matrix
break;
} else {
p++;
}
}
return rows;
}
int main() {
char line1[10000], line2[1000], line3[1000];
if (!fgets(line1, sizeof(line1), stdin)) return 1;
if (!fgets(line2, sizeof(line2), stdin)) return 1;
if (!fgets(line3, sizeof(line3), stdin)) return 1;
int n;
int m = parseMatrix(line1, maze_data, &n);
int* maze[100];
for (int i = 0; i < m; i++) {
maze[i] = maze_data[i];
}
int start[10], destination[10];
int start_size, dest_size;
parseArray(line2, start, &start_size);
parseArray(line3, destination, &dest_size);
int result = solution(maze, m, n, start, destination);
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
⚡ Linearithmic
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.