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
✓
Breadth-First Search (Optimal)
⏱️ Time: O(m×n)
Space: O(m×n)
BFS explores all cells at distance 1, then distance 2, and so on. The first exit reached is guaranteed to be at minimum distance.
Brute Force DFS
⏱️ Time: O(4^(m×n))
Space: O(m×n)
Use depth-first search to explore every possible path from entrance to all exits. Keep track of the minimum steps found among all valid paths.
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>
// --- Data Structures ---
typedef struct {
int row, col, steps;
} Node;
typedef struct {
Node *data;
int front, back, capacity;
} Queue;
Queue *createQueue(int capacity) {
Queue *q = malloc(sizeof(Queue));
if (!q) return NULL;
q->data = malloc(sizeof(Node) * capacity);
q->front = 0;
q->back = 0;
q->capacity = capacity;
return q;
}
void enqueue(Queue *q, int row, int col, int steps) {
if (q->back < q->capacity) {
q->data[q->back++] = (Node){row, col, steps};
}
}
Node dequeue(Queue *q) {
return q->data[q->front++];
}
int queueEmpty(Queue *q) {
return q->front == q->back;
}
void freeQueue(Queue *q) {
if (q) {
free(q->data);
free(q);
}
}
// --- Solution Logic (BFS) ---
int solution(char **maze, int m, int n, int startRow, int startCol) {
if (m == 0 || n == 0) return -1;
// Visited array to prevent loops
int *visited = calloc(m * n, sizeof(int));
if (!visited) return -1;
Queue *q = createQueue(m * n);
if (!q) { free(visited); return -1; }
enqueue(q, startRow, startCol, 0);
visited[startRow * n + startCol] = 1;
int dirs[4][2] = {{0,1},{1,0},{0,-1},{-1,0}};
while (!queueEmpty(q)) {
Node cur = dequeue(q);
int row = cur.row;
int col = cur.col;
int steps = cur.steps;
// Check if this is an exit (boundary cell that is NOT the start)
// Note: The problem usually defines an exit as an empty cell '.' on the boundary
if ((row == 0 || row == m-1 || col == 0 || col == n-1) &&
(row != startRow || col != startCol)) {
free(visited);
freeQueue(q);
return steps;
}
// Explore neighbors
for (int d = 0; d < 4; d++) {
int nr = row + dirs[d][0];
int nc = col + dirs[d][1];
// Check bounds
if (nr >= 0 && nr < m && nc >= 0 && nc < n) {
// Check walls and visited
if (maze[nr][nc] == '.' && !visited[nr * n + nc]) {
visited[nr * n + nc] = 1;
enqueue(q, nr, nc, steps + 1);
}
}
}
}
free(visited);
freeQueue(q);
return -1;
}
// --- Parsing Logic ---
// Parse a string like [["+","."], [".","."]] into a char** array
// This parser is robust against spaces, quotes, and commas.
char **parseMaze(char *line, int *outM, int *outN) {
// 1. Calculate number of rows (count occurrences of '[')
// We start m at -1 because the outer array has a '[' as well.
int m = -1;
char *p = line;
while (*p) {
if (*p == '[') m++;
p++;
}
if (m <= 0) { *outM = 0; *outN = 0; return NULL; }
char **maze = malloc(sizeof(char*) * m);
int row = 0;
int col = 0;
int maxCol = 0;
// 2. Parse content
// Find the first opening bracket
p = strchr(line, '[');
if (!p) return NULL;
p++;
// Temporary row buffer
char rowBuf[1024];
int inRow = 0;
while (*p) {
if (*p == '[') {
inRow = 1;
col = 0;
} else if (*p == ']') {
if (inRow) {
// End of a row
maze[row] = malloc(col * sizeof(char));
memcpy(maze[row], rowBuf, col);
if (col > maxCol) maxCol = col;
row++;
inRow = 0;
}
} else if (inRow) {
// Only capture valid maze characters
if (*p == '+' || *p == '.') {
rowBuf[col++] = *p;
}
}
p++;
}
*outM = row;
*outN = maxCol;
return maze;
}
void parseEntrance(char *line, int *row, int *col) {
// Look for format [row,col]
char *start = strchr(line, '[');
if (start) {
sscanf(start + 1, "%d,%d", row, col);
} else {
*row = 0; *col = 0;
}
}
// --- Main ---
int main(void) {
char line[100000];
// Read Maze Line
if (!fgets(line, sizeof(line), stdin)) return 0;
int m, n;
char **maze = parseMaze(line, &m, &n);
// Read Entrance Line
if (!fgets(line, sizeof(line), stdin)) return 0;
int startRow, startCol;
parseEntrance(line, &startRow, &startCol);
// Solve
if (maze) {
int result = solution(maze, m, n, startRow, startCol);
printf("%d\n", result);
// Cleanup
for (int i = 0; i < m; i++) free(maze[i]);
free(maze);
} else {
printf("-1\n");
}
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.