|  | 
|  | 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