You are given an m x n matrix maze (0-indexed) with empty cells (represented as '.') and walls (represented as '+'). You are also given the entrance of the maze, where entrance = [entrancerow, entrancecol] denotes the row and column of the cell you are initially standing at.
In one step, you can move one cell up, down, left, or right. You cannot step into a cell with a wall, and you cannot step outside the maze. Your goal is to find the nearest exit from the entrance. An exit is defined as an empty cell that is at the border of the maze. The entrance does not count as an exit.
Return the number of steps in the shortest path from the entrance to the nearest exit, or -1 if no such path exists.
💡 Note:Start at (1,0). Although this is a border cell, it's the entrance so doesn't count as exit. All other border cells are walls (+), so no exit exists.
The key insight is to use BFS for shortest path problems. BFS explores cells level by level, guaranteeing that the first exit found is at minimum distance. Best approach is BFS with queue. Time: O(m×n), Space: O(m×n)
Common Approaches
Approach
Time
Space
Notes
✓
Breadth-First Search (Optimal)
O(m×n)
O(m×n)
Use BFS to find shortest path by exploring cells level by level
Brute Force DFS
O(4^(m×n))
O(m×n)
Try all possible paths using DFS and track minimum steps to any exit
Breadth-First Search (Optimal) — Algorithm Steps
Start BFS from entrance using a queue
Explore all adjacent empty cells level by level
Mark visited cells to avoid revisiting
Return steps when first exit (border cell) is found
Visualization
Tap to expand
Step-by-Step Walkthrough
1
Level 0
Start at entrance, add to queue
2
Level 1
Explore all adjacent cells, add unvisited to queue
3
Level 2
Continue until exit found - guaranteed shortest
Code -
solution.c — C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct QueueNode {
int row, col, steps;
struct QueueNode* next;
};
struct Queue {
struct QueueNode* front;
struct QueueNode* rear;
};
void enqueue(struct Queue* q, int row, int col, int steps) {
struct QueueNode* newNode = (struct QueueNode*)malloc(sizeof(struct QueueNode));
newNode->row = row;
newNode->col = col;
newNode->steps = steps;
newNode->next = NULL;
if (q->rear == NULL) {
q->front = q->rear = newNode;
} else {
q->rear->next = newNode;
q->rear = newNode;
}
}
struct QueueNode* dequeue(struct Queue* q) {
if (q->front == NULL) return NULL;
struct QueueNode* temp = q->front;
q->front = q->front->next;
if (q->front == NULL) q->rear = NULL;
return temp;
}
int isEmpty(struct Queue* q) {
return q->front == NULL;
}
int solution(char maze[][1000], int m, int n, int* entrance) {
int startRow = entrance[0], startCol = entrance[1];
struct Queue q = {NULL, NULL};
int visited[1000][1000];
memset(visited, 0, sizeof(visited));
enqueue(&q, startRow, startCol, 0);
visited[startRow][startCol] = 1;
int directions[4][2] = {{0,1}, {1,0}, {0,-1}, {-1,0}};
while (!isEmpty(&q)) {
struct QueueNode* current = dequeue(&q);
int row = current->row, col = current->col, steps = current->steps;
if ((row == 0 || row == m-1 || col == 0 || col == n-1) &&
(row != startRow || col != startCol)) {
free(current);
return steps;
}
for (int i = 0; i < 4; i++) {
int newRow = row + directions[i][0];
int newCol = col + directions[i][1];
if (newRow >= 0 && newRow < m && newCol >= 0 && newCol < n &&
maze[newRow][newCol] == '.' && !visited[newRow][newCol]) {
visited[newRow][newCol] = 1;
enqueue(&q, newRow, newCol, steps + 1);
}
}
free(current);
}
return -1;
}
int main() {
char maze[1000][1000];
int entrance[2] = {1, 0};
int m = 3, n = 3;
// Example maze
maze[0][0] = '+'; maze[0][1] = '+'; maze[0][2] = '.';
maze[1][0] = '.'; maze[1][1] = '.'; maze[1][2] = '.';
maze[2][0] = '+'; maze[2][1] = '.'; maze[2][2] = '.';
printf("%d\n", solution(maze, m, n, entrance));
return 0;
}
Time & Space Complexity
Time Complexity
⏱️
O(m×n)
Each cell is visited at most once during BFS traversal
n
2n
✓ Linear Growth
Space Complexity
O(m×n)
Queue can hold up to m×n cells, plus visited array of size m×n
n
2n
⚡ Linearithmic Space
32.4K Views
MediumFrequency
~15 minAvg. Time
867 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.