Skip to content

Commit b564da5

Browse files
committedApr 3, 2025
Add solution #1091
1 parent 674d430 commit b564da5

File tree

2 files changed

+49
-1
lines changed

2 files changed

+49
-1
lines changed
 

‎README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# 1,130 LeetCode solutions in JavaScript
1+
# 1,131 LeetCode solutions in JavaScript
22

33
[https://leetcodejavascript.com](https://leetcodejavascript.com)
44

@@ -871,6 +871,7 @@
871871
1081|[Smallest Subsequence of Distinct Characters](./solutions/1081-smallest-subsequence-of-distinct-characters.js)|Medium|
872872
1089|[Duplicate Zeros](./solutions/1089-duplicate-zeros.js)|Easy|
873873
1090|[Largest Values From Labels](./solutions/1090-largest-values-from-labels.js)|Medium|
874+
1091|[Shortest Path in Binary Matrix](./solutions/1091-shortest-path-in-binary-matrix.js)|Medium|
874875
1092|[Shortest Common Supersequence](./solutions/1092-shortest-common-supersequence.js)|Hard|
875876
1103|[Distribute Candies to People](./solutions/1103-distribute-candies-to-people.js)|Easy|
876877
1108|[Defanging an IP Address](./solutions/1108-defanging-an-ip-address.js)|Easy|
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
/**
2+
* 1091. Shortest Path in Binary Matrix
3+
* https://leetcode.com/problems/shortest-path-in-binary-matrix/
4+
* Difficulty: Medium
5+
*
6+
* Given an n x n binary matrix grid, return the length of the shortest clear path in the matrix.
7+
* If there is no clear path, return -1.
8+
*
9+
* A clear path in a binary matrix is a path from the top-left cell (i.e., (0, 0)) to the
10+
* bottom-right cell (i.e., (n - 1, n - 1)) such that:
11+
* - All the visited cells of the path are 0.
12+
* - All the adjacent cells of the path are 8-directionally connected (i.e., they are different
13+
* and they share an edge or a corner).
14+
*
15+
* The length of a clear path is the number of visited cells of this path.
16+
*/
17+
18+
/**
19+
* @param {number[][]} grid
20+
* @return {number}
21+
*/
22+
var shortestPathBinaryMatrix = function(grid) {
23+
const size = grid.length;
24+
if (grid[0][0] === 1 || grid[size - 1][size - 1] === 1) return -1;
25+
26+
const queue = [[0, 0, 1]];
27+
const directions = [[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1, 1]];
28+
grid[0][0] = 1;
29+
30+
while (queue.length) {
31+
const [row, col, distance] = queue.shift();
32+
if (row === size - 1 && col === size - 1) return distance;
33+
34+
for (const [deltaRow, deltaCol] of directions) {
35+
const newRow = row + deltaRow;
36+
const newCol = col + deltaCol;
37+
38+
if (newRow >= 0 && newRow < size && newCol >= 0
39+
&& newCol < size && grid[newRow][newCol] === 0) {
40+
queue.push([newRow, newCol, distance + 1]);
41+
grid[newRow][newCol] = 1;
42+
}
43+
}
44+
}
45+
46+
return -1;
47+
};

0 commit comments

Comments
 (0)
Please sign in to comment.