Skip to content

Commit 15c8ce1

Browse files
committed
Add solution #1926
1 parent e32cda9 commit 15c8ce1

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -504,6 +504,7 @@
504504
1886|[Determine Whether Matrix Can Be Obtained By Rotation](./1886-determine-whether-matrix-can-be-obtained-by-rotation.js)|Easy|
505505
1910|[Remove All Occurrences of a Substring](./1910-remove-all-occurrences-of-a-substring.js)|Medium|
506506
1920|[Build Array from Permutation](./1920-build-array-from-permutation.js)|Easy|
507+
1926|[Nearest Exit from Entrance in Maze](./1926-nearest-exit-from-entrance-in-maze.js)|Medium|
507508
1929|[Concatenation of Array](./1929-concatenation-of-array.js)|Easy|
508509
1935|[Maximum Number of Words You Can Type](./1935-maximum-number-of-words-you-can-type.js)|Easy|
509510
1985|[Find the Kth Largest Integer in the Array](./1985-find-the-kth-largest-integer-in-the-array.js)|Medium|
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/**
2+
* 1926. Nearest Exit from Entrance in Maze
3+
* https://leetcode.com/problems/nearest-exit-from-entrance-in-maze/
4+
* Difficulty: Medium
5+
*
6+
* You are given an m x n matrix maze (0-indexed) with empty cells (represented as '.') and
7+
* walls (represented as '+'). You are also given the entrance of the maze, where entrance
8+
* = [entrancerow, entrancecol] denotes the row and column of the cell you are initially
9+
* standing at.
10+
*
11+
* In one step, you can move one cell up, down, left, or right. You cannot step into a cell
12+
* with a wall, and you cannot step outside the maze. Your goal is to find the nearest exit
13+
* from the entrance. An exit is defined as an empty cell that is at the border of the maze.
14+
* The entrance does not count as an exit.
15+
*
16+
* Return the number of steps in the shortest path from the entrance to the nearest exit,
17+
* or -1 if no such path exists.
18+
*/
19+
20+
/**
21+
* @param {character[][]} maze
22+
* @param {number[]} entrance
23+
* @return {number}
24+
*/
25+
var nearestExit = function(maze, entrance) {
26+
const queue = [[entrance, 0]];
27+
28+
while (queue.length) {
29+
const [cell, steps] = queue.shift();
30+
const [i, j] = cell;
31+
if (i === maze.length || i === -1 || j === maze[0].length || j === -1 || maze[i][j] !== '.') {
32+
continue;
33+
}
34+
if ((i === maze.length - 1 || i === 0 || j === maze[0].length - 1 || j === 0) && steps !== 0) {
35+
return steps;
36+
}
37+
maze[i][j] = '*';
38+
queue.push([[i, j + 1], steps + 1]);
39+
queue.push([[i, j - 1], steps + 1]);
40+
queue.push([[i + 1, j], steps + 1]);
41+
queue.push([[i - 1, j], steps + 1]);
42+
}
43+
44+
return -1;
45+
};

0 commit comments

Comments
 (0)