Re: [閒聊] 每日leetcode

看板Marginalman作者 (神楽めあ的錢包)時間2月前 (2025/10/06 17:01), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串1529/1548 (看更多)
778. Swim in Rising Water 思路: 用一個minimum heap來記錄目前到過的點哪個點海拔最低 每次都把海拔最低的點pop出來 並且記錄這些被pop出來的海拔中最大值 當抵達右下角時就可以停了 最後回傳這條路徑中最大的海拔 golang code : type point struct { x int y int } type maxHeap struct { arr []point grid [][]int } func (this maxHeap) Len() int { return len(this.arr) } func (this maxHeap) Less(i, j int) bool { return this.grid[this.arr[i].x][this.arr[i].y] < this.grid[this.arr[j].x][ this.arr[j].y] } func (this maxHeap) Swap(i, j int) { this.arr[i], this.arr[j] = this.arr[j], this.arr[i] } func (this *maxHeap) Pop() interface{} { n := len(this.arr) res := this.arr[n-1] (*this).arr = (*this).arr[:n-1] return res } func (this *maxHeap) Push(x interface{}) { (*this).arr = append((*this).arr, x.(point)) } func swimInWater(grid [][]int) int { h := maxHeap{[]point{}, grid} n, m := len(grid), len(grid[0]) heap.Push(&h, point{0, 0}) ans := 0 direction, visit := [][]int{{1, 0}, {-1, 0}, {0, 1}, {0, -1}}, make([]bool, n *m) visit[0] = true for { curPoint := heap.Pop(&h).(point) ans = max(ans, grid[curPoint.x][curPoint.y]) if curPoint.x == n-1 && curPoint.y == m-1 { break } for _, val := range direction { nextX := curPoint.x + val[0] nextY := curPoint.y + val[1] if nextX > -1 && nextY > -1 && nextX < n && nextY < m && !visit[nextX*m+ nextY] { visit[nextX*m+nextY] = true heap.Push(&h, point{nextX, nextY}) } } } return ans } -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 203.121.235.241 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1759741306.A.20B.html
文章代碼(AID): #1euuLw8B (Marginalman)
討論串 (同標題文章)
文章代碼(AID): #1euuLw8B (Marginalman)