Skip to content

Commit

Permalink
Merge pull request youngyangyang04#2828 from catherinexrk/master
Browse files Browse the repository at this point in the history
图论103.md水流问题 提交Go的DFS方案
  • Loading branch information
youngyangyang04 authored Dec 18, 2024
2 parents bf0309f + a982d2d commit 21a3215
Showing 1 changed file with 75 additions and 0 deletions.
75 changes: 75 additions & 0 deletions problems/kamacoder/0103.水流问题.md
Original file line number Diff line number Diff line change
Expand Up @@ -413,6 +413,81 @@ if __name__ == "__main__":
```

### 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

Expand Down

0 comments on commit 21a3215

Please sign in to comment.