Table of Contents
Problem
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.
Example 1:
Input: maze = [["+","+",".","+"],[".",".",".","+"],["+","+","+","."]], entrance = [1,2] Output: 1 Explanation: There are 3 exits in this maze at [1,0], [0,2], and [2,3]. Initially, you are at the entrance cell [1,2]. - You can reach [1,0] by moving 2 steps left. - You can reach [0,2] by moving 1 step up. It is impossible to reach [2,3] from the entrance. Thus, the nearest exit is [0,2], which is 1 step away.
Example 2:
Input: maze = [["+","+","+"],[".",".","."],["+","+","+"]], entrance = [1,0] Output: 2 Explanation: There is 1 exit in this maze at [1,2]. [1,0] does not count as an exit since it is the entrance cell. Initially, you are at the entrance cell [1,0]. - You can reach [1,2] by moving 2 steps right. Thus, the nearest exit is [1,2], which is 2 steps away.
Example 3:
Input: maze = [[".","+"]], entrance = [0,0] Output: -1 Explanation: There are no exits in this maze.
Constraints:
maze.length == m
maze[i].length == n
1 <= m, n <= 100
maze[i][j]
is either'.'
or'+'
.entrance.length == 2
0 <= entrancerow < m
0 <= entrancecol < n
entrance
will always be an empty cell.
Source: Leetcode 1926. Nearest Exit from Entrance in Maze
Solution
This is a trivial BFS problem. If you do not know, BFS stands for Breadth First Search. This graph algorithm explores neighbouring nodes as one layer at a time. Then for each node of the first layer, it explores the second layer. This way, it doesn’t go deep into one path like Depth First Search algorithm does.
To apply BFS, we will use a queue and push the source coordinates into queue. Until queue is empty or any result node is not found, we will continue exploring layer by layer and keep track of visited nodes. Also we will update the distance of a newly explored node with respect to its parent node. We will do like, distance of source = distance of parent + 1.
Here is a simple C++ code for your understanding.
class Solution { public: int nearestExit(vector<vector<char>>& maze, vector<int>& entrance) { queue<pair<int, int>> q; q.push({entrance[0], entrance[1]}); // push the source node to queue int R = maze.size(); int C = maze[0].size(); vector<vector<int>> dir = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; vector<vector<int>> visited(101, vector<int>(101, -1)); // to keep track of explored or unexplored nodes, unexplored = -1 visited[entrance[0]][entrance[1]] = 0; while(!q.empty()){ pair<int, int> cur = q.front(); // current parent node q.pop(); for(int i = 0; i < 4; i++){ int new_x = cur.first + dir[i][0]; // Coordinates of New child to explored int new_y = cur.second + dir[i][1]; if(0 <= new_x && new_x < R && 0 <= new_y && new_y < C){ if(maze[new_x][new_y] == '.'){ // if it is a valid cell to move if(visited[new_x][new_y] == -1){ // and not visited already visited[new_x][new_y] = visited[cur.first][cur.second] + 1; // update child distance with +1 of parent (cur) if(new_x == 0 || new_x == R - 1 || new_y == 0 || new_y == C - 1) // Terminal condition found!!! Let's return :) return visited[new_x][new_y]; q.push({new_x, new_y}); //push this child to the queue } } } } } return -1; // cannot go our of maze, return -1! } };
Bonus – System Design!
ByteByteGo is by far the best system design resource found on the internet. They are growing like crazy!
We suggest you checkout their course if you really want to dive deep in system design and want to have a killer interview!
Here is the link: ByteByteGo!
Disclaimer: this is a genuine suggestion, but we have some interest too! We get commission if you buy their course. However, there are other courses online which we do not promote. Because we promote only things that are the best in our opinion and those we really feel will be helpful for you.
To the foolishhungry.com administrator, Thanks for the in-depth post!
Hi foolishhungry.com owner, Your posts are always a great read.
Dear foolishhungry.com webmaster, Your posts are always a great source of information.
To the foolishhungry.com webmaster, Your posts are always well-supported by facts and figures.
To the foolishhungry.com administrator, Your posts are always informative.
Hi foolishhungry.com webmaster, Your posts are always well researched and well written.
This blog is an invaluable source of information. I appreciate the standard of your posts.
Hello foolishhungry.com admin, Your posts are always well-delivered and engaging.
Hello foolishhungry.com webmaster, You always provide great examples and real-world applications.
To the foolishhungry.com admin, Your posts are always well researched and well written.
Thank you very much for sharing, I learned a lot from your article. Very cool. Thanks. nimabi
Dear foolishhungry.com admin, Thanks for the well-written and informative post!
Dear foolishhungry.com owner, Thanks for the well-structured and well-presented post!
Hello foolishhungry.com owner, Thanks for the well-organized post!
Hello foolishhungry.com webmaster, Your posts are always well-written and easy to understand.
I don’t think the title of your article matches the content lol. Just kidding, mainly because I had some doubts after reading the article. https://accounts.binance.com/bn/register?ref=W0BCQMF1
Your article helped me a lot, is there any more related content? Thanks!
To the foolishhungry.com administrator, Your posts are always well-supported and evidence-based.