Minimum Obstacle Removal to Reach Corner LeetCode solution in JavaScript

1
/**
2
* @param {number[][]} grid
3
* @return {number}
4
*/
5
var minimumObstacles = function (grid) {
6
let dx = [
7
[0, 1],
8
[0, -1],
9
[1, 0],
10
[-1, 0],
11
];
12
let distance = [];
13
for (let i = 0; i < grid.length; i++) {
14
distance[i] = [];
15
for (let j = 0; j < grid[i].length; j++) {
16
distance[i][j] = Number.MAX_SAFE_INTEGER;
17
}
18
}
19
return bfs(0, 0);
20

21
function bfs(row, col) {
22
let queue = [];
23
distance[row][col] = 0;
24
queue.push([row, col]);
25
while (queue.length > 0) {
26
let element = queue.shift();
27
let row = element[0];
28
let col = element[1];
29
let originalDist = distance[row][col];
30
for (let d = 0; d < dx.length; d++) {
31
let i = row + dx[d][0];
32
let j = col + dx[d][1];
33
if (
34
i >= 0 &&
35
i <= grid.length - 1 &&
36
j >= 0 &&
37
j <= grid[i].length - 1
38
) {
39
let dist = originalDist;
40
if (grid[i][j] === 1) {
41
dist++;
42
}
43
if (distance[i][j] > dist) {
44
//Update distance for this neighbour node if the new distance is smaller than the previous distance
45
queue.push([i, j]);
46
distance[i][j] = dist;
47
}
48
}
49
}
50
}
51
//return the minimum distance for last cell after completing the process
52
return distance[grid.length - 1][grid[row].length - 1];
53
}
54
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0