1368. Minimum Cost to Make at Least One Valid Path in a Grid Hard
1/**
2 * [1368] Minimum Cost to Make at Least One Valid Path in a Grid
3 *
4 * Given an m x n grid. Each cell of the grid has a sign pointing to the next cell you should visit if you are currently in this cell. The sign of grid[i][j] can be:
5 *
6 * 1 which means go to the cell to the right. (i.e go from grid[i][j] to grid[i][j + 1])
7 * 2 which means go to the cell to the left. (i.e go from grid[i][j] to grid[i][j - 1])
8 * 3 which means go to the lower cell. (i.e go from grid[i][j] to grid[i + 1][j])
9 * 4 which means go to the upper cell. (i.e go from grid[i][j] to grid[i - 1][j])
10 *
11 * Notice that there could be some signs on the cells of the grid that point outside the grid.
12 * 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.
13 * You can modify the sign on a cell with cost = 1. You can modify the sign on a cell one time only.
14 * Return the minimum cost to make the grid have at least one valid path.
15 *
16 * Example 1:
17 * <img alt="" src="https://assets.leetcode.com/uploads/2020/02/13/grid1.png" style="width: 400px; height: 390px;" />
18 * Input: grid = [[1,1,1,1],[2,2,2,2],[1,1,1,1],[2,2,2,2]]
19 * Output: 3
20 * Explanation: You will start at point (0, 0).
21 * The path to (3, 3) is as follows. (0, 0) --> (0, 1) --> (0, 2) --> (0, 3) change the arrow to down with cost = 1 --> (1, 3) --> (1, 2) --> (1, 1) --> (1, 0) change the arrow to down with cost = 1 --> (2, 0) --> (2, 1) --> (2, 2) --> (2, 3) change the arrow to down with cost = 1 --> (3, 3)
22 * The total cost = 3.
23 *
24 * Example 2:
25 * <img alt="" src="https://assets.leetcode.com/uploads/2020/02/13/grid2.png" style="width: 350px; height: 341px;" />
26 * Input: grid = [[1,1,3],[3,2,2],[1,1,4]]
27 * Output: 0
28 * Explanation: You can follow the path from (0, 0) to (2, 2).
29 *
30 * Example 3:
31 * <img alt="" src="https://assets.leetcode.com/uploads/2020/02/13/grid3.png" style="width: 200px; height: 192px;" />
32 * Input: grid = [[1,2],[4,3]]
33 * Output: 1
34 *
35 *
36 * Constraints:
37 *
38 * m == grid.length
39 * n == grid[i].length
40 * 1 <= m, n <= 100
41 * 1 <= grid[i][j] <= 4
42 *
43 */
44pub struct Solution {}
45
46// problem: https://leetcode.com/problems/minimum-cost-to-make-at-least-one-valid-path-in-a-grid/
47// discuss: https://leetcode.com/problems/minimum-cost-to-make-at-least-one-valid-path-in-a-grid/discuss/?currentPage=1&orderBy=most_votes&query=
48
49// submission codes start here
50
51impl Solution {
52 pub fn min_cost(grid: Vec<Vec<i32>>) -> i32 {
53 0
54 }
55}
56
57// submission codes end
58
59#[cfg(test)]
60mod tests {
61 use super::*;
62
63 #[test]
64 fn test_1368() {
65 }
66}
67
Back
© 2025 bowen.ge All Rights Reserved.