Minimum Cost to Make at Least One Valid Path in a Grid LeetCode solution in JavaScript

1
var minCost = function (grid) {
2
const n = grid.length;
3
const m = grid[0].length;
4
const dns = [
5
[0, 0], // unused, just put here to make reading signs easier
6
[1, 0],
7
[-1, 0],
8
[0, 1],
9
[0, -1],
10
];
11
const visited = new Set();
12
const q = new MinPriorityQueue();
13
q.enqueue([0, 0], 0);
14
while (q.size()) {
15
const { element, priority: changes } = q.dequeue();
16
const [x, y] = element;
17
if (x === m - 1 && y === n - 1) {
18
return changes;
19
}
20
const key = x + y * m;
21
if (visited.has(key)) continue;
22
visited.add(key);
23
//calculate the direction of the sign and then use it to determine if a change was made whilst pathfinding
24
const sign = grid[y][x];
25
const sx = dns[sign][0] + x;
26
const sy = dns[sign][1] + y;
27
for (let i = 1; i < 5; ++i) {
28
const nx = dns[i][0] + x;
29
const ny = dns[i][1] + y;
30
if (grid[ny]?.[nx] && !visited.has(ny * m + nx)) {
31
const nextChange = sx === nx && sy === ny ? changes : changes + 1;
32
q.enqueue([nx, ny], nextChange);
33
}
34
}
35
}
36
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0