|
| 1 | +/* |
| 2 | + * @Author: LetMeFly |
| 3 | + * @Date: 2025-10-06 12:17:42 |
| 4 | + * @LastEditors: LetMeFly.xyz |
| 5 | + * @LastEditTime: 2025-10-06 14:31:25 |
| 6 | + */ |
| 7 | +package main |
| 8 | + |
| 9 | +// The Wrong Version: should call heap.Pop(pq) but not pq.Pop() |
| 10 | + |
| 11 | +import "container/heap" |
| 12 | + |
| 13 | +type Item778 struct { |
| 14 | + x, y int |
| 15 | + val int |
| 16 | +} |
| 17 | + |
| 18 | +type PriorityQueue778 []*Item778 |
| 19 | + |
| 20 | +var directions778 = [][]int{{0, 1}, {0, -1}, {-1, 0}, {1, 0}} |
| 21 | + |
| 22 | +func swimInWater(grid [][]int) int { |
| 23 | + n, m := len(grid), len(grid[0]) |
| 24 | + if n == 1 && m == 1 { |
| 25 | + return grid[0][0] |
| 26 | + } |
| 27 | + visited := make([][]bool, n) |
| 28 | + for i, _ := range visited { |
| 29 | + visited[i] = make([]bool, m) |
| 30 | + } |
| 31 | + |
| 32 | + pq := &PriorityQueue778{} |
| 33 | + heap.Init(pq) |
| 34 | + pq.Push(&Item778{0, 0, grid[0][0]}) |
| 35 | + visited[0][0] = true |
| 36 | + for true { |
| 37 | + item := pq.Pop().(*Item778) |
| 38 | + x, y, val := item.x, item.y, item.val |
| 39 | + for _, d := range directions778 { |
| 40 | + nx, ny := x + d[0], y + d[1] |
| 41 | + if nx < 0 || nx >= n || ny < 0 || ny >= m || visited[nx][ny] { |
| 42 | + continue |
| 43 | + } |
| 44 | + grid[nx][ny] = max(grid[nx][ny], val) |
| 45 | + if nx == n - 1 && ny == m - 1 { |
| 46 | + return grid[nx][ny] |
| 47 | + } |
| 48 | + visited[nx][ny] = true |
| 49 | + pq.Push(&Item778{nx, ny, grid[nx][ny]}) |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + return -1 // Fake Return |
| 54 | +} |
| 55 | + |
| 56 | +func (pq PriorityQueue778) Len() int { return len(pq) } |
| 57 | +func (pq PriorityQueue778) Less(i, j int) bool { return pq[i].val < pq[j].val } |
| 58 | +func (pq PriorityQueue778) Swap(i, j int) { pq[i], pq[j] = pq[j], pq[i] } |
| 59 | +func (pq *PriorityQueue778) Push(x any) { *pq = append(*pq, x.(*Item778)) } |
| 60 | +func (pq *PriorityQueue778) Pop() any { n := len(*pq); item := (*pq)[n - 1]; *pq = (*pq)[:n-1]; return item } |
0 commit comments