|
| 1 | +/** |
| 2 | + * 1368. Minimum Cost to Make at Least One Valid Path in a Grid |
| 3 | + * https://leetcode.com/problems/minimum-cost-to-make-at-least-one-valid-path-in-a-grid/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * Given an m x n grid. Each cell of the grid has a sign pointing to the next cell you should |
| 7 | + * visit if you are currently in this cell. The sign of grid[i][j] can be: |
| 8 | + * - 1 which means go to the cell to the right. (i.e go from grid[i][j] to grid[i][j + 1]) |
| 9 | + * - 2 which means go to the cell to the left. (i.e go from grid[i][j] to grid[i][j - 1]) |
| 10 | + * - 3 which means go to the lower cell. (i.e go from grid[i][j] to grid[i + 1][j]) |
| 11 | + * - 4 which means go to the upper cell. (i.e go from grid[i][j] to grid[i - 1][j]) |
| 12 | + * |
| 13 | + * Notice that there could be some signs on the cells of the grid that point outside the grid. |
| 14 | + * |
| 15 | + * You will initially start at the upper left cell (0, 0). A valid path in the grid is a path |
| 16 | + * that starts from the upper left cell (0, 0) and ends at the bottom-right cell (m - 1, n - 1) |
| 17 | + * following the signs on the grid. The valid path does not have to be the shortest. |
| 18 | + * |
| 19 | + * You can modify the sign on a cell with cost = 1. You can modify the sign on a cell one time |
| 20 | + * only. |
| 21 | + * |
| 22 | + * Return the minimum cost to make the grid have at least one valid path. |
| 23 | + */ |
| 24 | + |
| 25 | +/** |
| 26 | + * @param {number[][]} grid |
| 27 | + * @return {number} |
| 28 | + */ |
| 29 | +var minCost = function(grid) { |
| 30 | + const queue = [[0, 0]]; |
| 31 | + const directions = [[0, 1, 1], [0, -1, 2], [1, 0, 3], [-1, 0, 4]]; |
| 32 | + const bfs = grid.map(r => r.map(_ => Infinity)); |
| 33 | + bfs[0][0] = 0; |
| 34 | + |
| 35 | + while (queue.length > 0) { |
| 36 | + const [x, y] = queue.shift(); |
| 37 | + for (const [dx, dy, value] of directions) { |
| 38 | + const [cX, cY] = [x + dx, y + dy]; |
| 39 | + if (grid[cX]?.[cY]) { |
| 40 | + const updatedValue = bfs[x][y] + (grid[x][y] !== value); |
| 41 | + if (updatedValue < bfs[cX][cY]) { |
| 42 | + bfs[cX][cY] = updatedValue; |
| 43 | + queue.push([cX, cY]); |
| 44 | + } |
| 45 | + } |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + return bfs.at(-1).at(-1); |
| 50 | +}; |
0 commit comments