添加 0103.水流问题. Go语言 DFS版本

This commit is contained in:
陶笛
2024-11-12 10:52:30 +08:00
committed by GitHub
parent aeff1d6ad9
commit 947424d311

View File

@ -413,6 +413,81 @@ if __name__ == "__main__":
``` ```
### Go ### Go
```go
package main
import (
"os"
"fmt"
"strings"
"strconv"
"bufio"
)
var directions = [][]int{{0, -1}, {0, 1}, {-1, 0}, {1, 0}} // 四个方向的偏移量
func main() {
scanner := bufio.NewScanner(os.Stdin)
scanner.Scan()
lineList := strings.Fields(scanner.Text())
N, _ := strconv.Atoi(lineList[0])
M, _ := strconv.Atoi(lineList[1])
grid := make([][]int, N)
visited := make([][]bool, N) // 用于标记是否访问过
for i := 0; i < N; i++ {
grid[i] = make([]int, M)
visited[i] = make([]bool, M)
scanner.Scan()
lineList = strings.Fields(scanner.Text())
for j := 0; j < M; j++ {
grid[i][j], _ = strconv.Atoi(lineList[j])
}
}
// 遍历每个单元格使用DFS检查是否可达两组边界
for i := 0; i < N; i++ {
for j := 0; j < M; j++ {
canReachFirst, canReachSecond := dfs(grid, visited, i, j)
if canReachFirst && canReachSecond {
fmt.Println(strconv.Itoa(i) + " " + strconv.Itoa(j))
}
}
}
}
func dfs(grid [][]int, visited [][]bool, startx int, starty int) (bool, bool) {
visited[startx][starty] = true
canReachFirst := startx == 0 || starty == 0 || startx == len(grid)-1 || starty == len(grid[0])-1
canReachSecond := startx == len(grid)-1 || starty == len(grid[0])-1 || startx == 0 || starty == 0
if canReachFirst && canReachSecond {
return true, true
}
for _, direction := range directions {
nextx := startx + direction[0]
nexty := starty + direction[1]
if nextx < 0 || nextx >= len(grid) || nexty < 0 || nexty >= len(grid[0]) {
continue
}
if grid[nextx][nexty] <= grid[startx][starty] && !visited[nextx][nexty] {
hasReachFirst, hasReachSecond := dfs(grid, visited, nextx, nexty)
if !canReachFirst {
canReachFirst = hasReachFirst
}
if !canReachSecond {
canReachSecond = hasReachSecond
}
}
}
return canReachFirst, canReachSecond
}
```
### Rust ### Rust