二维接雨水
![](https://img2022.cnblogs.com/blog/1468919/202206/1468919-20220620155142153-2017469343.png)
https://leetcode.cn/problems/trapping-rain-water-ii/
func trapRainWater(heightMap [][]int) int { m, n := len(heightMap), len(heightMap[0]) maxHeight := 0 for _, row := range heightMap {//找到最高的格子 for _, h := range row { maxHeight = max(maxHeight, h) } } water := make([][]int,m) for i := range water {//初始化每个位置的高度都为最大 water[i] = make([]int, n) for j := range water[i] { water[i][j] = maxHeight } } type xy struct{ x, y int } q := []xy{} //bfs队列 for i := range heightMap { for j:= range heightMap[i] { if (i == 0 || i == m-1 || j == 0 || j == n-1) && heightMap[i][j] < water[i][j] { water[i][j] = heightMap[i][j]//最外层方块不能接水 q = append(q, xy{i, j}) //bfs入口,从最外层开始搜索 } } } dirs := []int{-1, 0, 1, 0, -1}//四方向搜索 for len(q) > 0 { p := q[0] q = q[1:] x, y := p.x, p.y for i := 0; i < 4; i++ { nx, ny := x+dirs[i], y+dirs[i+1] //1、位置合法 2、搜索位置比当前维护的最大高度要高 3、搜索位置比当前位置要高 if 0 <= nx && nx < m && 0 <= ny && ny < n && water[nx][ny] > water[x][y] && water[nx][ny] > heightMap[nx][ny] { water[nx][ny] = max(water[x][y], heightMap[nx][ny]) q = append(q, xy{nx, ny}) } } } ans:=0 for i := range heightMap { for j := range heightMap[i] { ans += water[i][j] - heightMap[i][j] } } return ans } func max(a, b int) int { if b > a { return b } return a }
等风起的那一天,我已准备好一切