Skip to content

Commit 51999f5

Browse files
authored
Merge pull request #1246 from harshitcompcode/patch-1
Create distance_of_nearest_zero.js
2 parents 0f01c9e + 3aa035a commit 51999f5

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
Example:
2+
Input: mat = [[0,0,0],[0,1,0],[0,0,0]]
3+
Output: [[0,0,0],[0,1,0],[0,0,0]]
4+
5+
It can be solved using a Breadth First Search Algorithm(BFS)
6+
7+
function updateMatrix(mat) {
8+
const m = mat.length;
9+
const n = mat[0].length;
10+
const queue = [];
11+
12+
// Initialize distance matrix with maximum possible values
13+
const dist = new Array(m).fill().map(() => new Array(n).fill(Number.MAX_VALUE));
14+
15+
// Initialize the queue with all cells containing 0
16+
for (let i = 0; i < m; i++) {
17+
for (let j = 0; j < n; j++) {
18+
if (mat[i][j] === 0) {
19+
dist[i][j] = 0;
20+
queue.push([i, j]);
21+
}
22+
}
23+
}
24+
25+
// Perform a BFS starting from the cells containing 0
26+
while (queue.length > 0) {
27+
const [i, j] = queue.shift();
28+
29+
// Check the neighbors of the current cell
30+
const neighbors = [[i - 1, j], [i + 1, j], [i, j - 1], [i, j + 1]];
31+
for (const [ni, nj] of neighbors) {
32+
// Check if the neighbor is within bounds
33+
if (ni >= 0 && ni < m && nj >= 0 && nj < n) {
34+
// If the distance to the neighbor can be updated
35+
if (dist[ni][nj] > dist[i][j] + 1) {
36+
dist[ni][nj] = dist[i][j] + 1;
37+
queue.push([ni, nj]);
38+
}
39+
}
40+
}
41+
}
42+
43+
return dist;
44+
}
45+
46+
47+
The updateMatrix function takes a binary matrix mat as input and returns a matrix dist with the distance of the nearest 0 for each cell.
48+
The algorithm first initializes the dist matrix with maximum possible values and adds all cells containing 0 to a queue.
49+
Then, it performs a BFS starting from the cells in the queue and updates the distances of the neighboring cells if they can be improved.
50+
Finally, it returns the dist matrix with the updated distances.

0 commit comments

Comments
 (0)