Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 6b6afbd

Browse files
author
hasibulislam999
committed
Minimum Cost to Make at Least One Valid Path in a Grid problem solved
1 parent 6d7d5b3 commit 6b6afbd

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/**
2+
* Title: Minimum Cost to Make at Least One Valid Path in a Grid
3+
* Description: You will initially start at the upper left cell (0, 0). A valid path in the grid is a path that starts from the upper left cell (0, 0) and ends at the bottom-right cell (m - 1, n - 1) following the signs on the grid. The valid path does not have to be the shortest.
4+
* Author: Hasibul Islam
5+
* Date: 04/05/2023
6+
*/
7+
8+
/**
9+
* @param {number[][]} grid
10+
* @return {number}
11+
*/
12+
const minCost = function (grid) {
13+
const m = grid.length,
14+
n = grid[0].length,
15+
checkPos = (i, j) =>
16+
i > -1 && j > -1 && i < m && j < n && !visited[i + "," + j],
17+
dir = { 1: [0, 1], 2: [0, -1], 3: [1, 0], 4: [-1, 0] },
18+
dfs = (i, j) => {
19+
if (!checkPos(i, j)) return false;
20+
if (i === m - 1 && j === n - 1) return true;
21+
visited[i + "," + j] = true;
22+
next.push([i, j]);
23+
return dfs(i + dir[grid[i][j]][0], j + dir[grid[i][j]][1]);
24+
},
25+
visited = {};
26+
let changes = 0,
27+
cur = [[0, 0]],
28+
next;
29+
while (cur.length) {
30+
next = [];
31+
for (const [i, j] of cur) if (dfs(i, j)) return changes;
32+
changes++;
33+
cur = [];
34+
next.forEach((pos) => {
35+
for (let d = 1; d < 5; d++) {
36+
const x = pos[0] + dir[d][0],
37+
y = pos[1] + dir[d][1];
38+
if (checkPos(x, y)) cur.push([x, y]);
39+
}
40+
});
41+
}
42+
};

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /