Skip to content

Commit 10428e2

Browse files
authored
Create 1368-minimum-cost-to-make-at-least-one-valid-path-in-a-grid.js
1 parent 338883a commit 10428e2

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/**
2+
* @param {number[][]} grid
3+
* @return {number}
4+
*/
5+
const minCost = function (grid) {
6+
const n = grid.length
7+
const m = grid[0].length
8+
const moves = [
9+
[0, 1],
10+
[0, -1],
11+
[1, 0],
12+
[-1, 0],
13+
]
14+
const dp = [...new Array(n)].map((e) => [...new Array(m)].fill(Infinity))
15+
dp[0][0] = 0
16+
let queue = [[0, 0]]
17+
while (queue.length > 0) {
18+
const temp = []
19+
for (let i = 0; i < queue.length; i++) {
20+
const [x, y] = queue[i]
21+
for (let j = 0; j < moves.length; j++) {
22+
const nextX = x + moves[j][0]
23+
const nextY = y + moves[j][1]
24+
if (nextX >= 0 && nextY >= 0 && nextX < n && nextY < m) {
25+
if (dp[nextX][nextY] > dp[x][y] + (grid[x][y] - 1 === j ? 0 : 1)) {
26+
dp[nextX][nextY] = dp[x][y] + (grid[x][y] - 1 === j ? 0 : 1)
27+
queue.push([nextX, nextY])
28+
}
29+
}
30+
}
31+
}
32+
queue = temp
33+
}
34+
return dp[n - 1][m - 1]
35+
}

0 commit comments

Comments
 (0)