|
| 1 | +// https://leetcode.com/problems/minimum-cost-to-make-at-least-one-valid-path-in-a-grid/description/ |
| 2 | + |
| 3 | +package main |
| 4 | + |
| 5 | +import ( |
| 6 | + "container/list" |
| 7 | + "fmt" |
| 8 | +) |
| 9 | + |
| 10 | +func minCost(grid [][]int) int { |
| 11 | + m, n := len(grid), len(grid[0]) |
| 12 | + // define directions |
| 13 | + dirs := [4][2]int{ |
| 14 | + {0, 1}, // right |
| 15 | + {0, -1}, // left |
| 16 | + {1, 0}, // down |
| 17 | + {-1, 0}, // up |
| 18 | + } |
| 19 | + |
| 20 | + // init cost |
| 21 | + costs := make([][]int, m) |
| 22 | + for i := range costs { |
| 23 | + costs[i] = make([]int, n) |
| 24 | + for j := range costs[i] { |
| 25 | + costs[i][j] = 1 << 30 |
| 26 | + } |
| 27 | + } |
| 28 | + costs[0][0] = 0 // start point cost is 0 |
| 29 | + |
| 30 | + // define dqueue |
| 31 | + dq := list.New() |
| 32 | + dq.PushBack([3]int{0, 0, 0}) // [x, y, cost] |
| 33 | + |
| 34 | + // bfs |
| 35 | + for dq.Len() > 0 { |
| 36 | + node := dq.Remove(dq.Front()).([3]int) |
| 37 | + x, y, cost := node[0], node[1], node[2] |
| 38 | + |
| 39 | + // if reach the end point, return the cost |
| 40 | + if x == m-1 && y == n-1 { |
| 41 | + return cost |
| 42 | + } |
| 43 | + |
| 44 | + // try all directions |
| 45 | + for i, dir := range dirs { |
| 46 | + nx, ny := x+dir[0], y+dir[1] |
| 47 | + if nx >= 0 && nx < m && ny >= 0 && ny < n { // Nếu ô mới nằm trong lưới |
| 48 | + newCost := cost |
| 49 | + if grid[x][y] != i+1 { // Nếu hướng sai, tăng chi phí |
| 50 | + newCost++ |
| 51 | + } |
| 52 | + |
| 53 | + // Nếu tìm được đường đi với chi phí thấp hơn |
| 54 | + if newCost < costs[nx][ny] { |
| 55 | + costs[nx][ny] = newCost |
| 56 | + if grid[x][y] == i+1 { |
| 57 | + dq.PushFront([3]int{nx, ny, newCost}) // Ưu tiên chi phí 0 |
| 58 | + } else { |
| 59 | + dq.PushBack([3]int{nx, ny, newCost}) // Chi phí 1 thêm vào sau |
| 60 | + } |
| 61 | + } |
| 62 | + } |
| 63 | + } |
| 64 | + } |
| 65 | + |
| 66 | + return -1 |
| 67 | +} |
| 68 | + |
| 69 | +func main() { |
| 70 | + grid1 := [][]int{ |
| 71 | + {1, 1, 3}, |
| 72 | + {3, 2, 2}, |
| 73 | + {1, 1, 4}, |
| 74 | + } |
| 75 | + fmt.Println(minCost(grid1)) // Output: 0 |
| 76 | + |
| 77 | + grid2 := [][]int{ |
| 78 | + {1, 1, 1, 1}, |
| 79 | + {2, 2, 2, 2}, |
| 80 | + {1, 1, 1, 1}, |
| 81 | + {2, 2, 2, 2}, |
| 82 | + } |
| 83 | + fmt.Println(minCost(grid2)) // Output: 3 |
| 84 | +} |
0 commit comments