@@ -413,6 +413,81 @@ if __name__ == "__main__":
413413```
414414
415415### Go
416+ ``` go
417+ package main
418+
419+ import (
420+ " os"
421+ " fmt"
422+ " strings"
423+ " strconv"
424+ " bufio"
425+ )
426+
427+ var directions = [][]int {{0 , -1 }, {0 , 1 }, {-1 , 0 }, {1 , 0 }} // 四个方向的偏移量
428+
429+ func main () {
430+ scanner := bufio.NewScanner (os.Stdin )
431+
432+ scanner.Scan ()
433+ lineList := strings.Fields (scanner.Text ())
434+ N , _ := strconv.Atoi (lineList[0 ])
435+ M , _ := strconv.Atoi (lineList[1 ])
436+
437+ grid := make ([][]int , N)
438+ visited := make ([][]bool , N) // 用于标记是否访问过
439+ for i := 0 ; i < N; i++ {
440+ grid[i] = make ([]int , M)
441+ visited[i] = make ([]bool , M)
442+ scanner.Scan ()
443+ lineList = strings.Fields (scanner.Text ())
444+
445+ for j := 0 ; j < M; j++ {
446+ grid[i][j], _ = strconv.Atoi (lineList[j])
447+ }
448+ }
449+
450+ // 遍历每个单元格,使用DFS检查是否可达两组边界
451+ for i := 0 ; i < N; i++ {
452+ for j := 0 ; j < M; j++ {
453+ canReachFirst , canReachSecond := dfs (grid, visited, i, j)
454+ if canReachFirst && canReachSecond {
455+ fmt.Println (strconv.Itoa (i) + " " + strconv.Itoa (j))
456+ }
457+ }
458+ }
459+ }
460+
461+ func dfs (grid [][]int , visited [][]bool , startx int , starty int ) (bool , bool ) {
462+ visited[startx][starty] = true
463+ canReachFirst := startx == 0 || starty == 0 || startx == len (grid)-1 || starty == len (grid[0 ])-1
464+ canReachSecond := startx == len (grid)-1 || starty == len (grid[0 ])-1 || startx == 0 || starty == 0
465+
466+ if canReachFirst && canReachSecond {
467+ return true , true
468+ }
469+
470+ for _ , direction := range directions {
471+ nextx := startx + direction[0 ]
472+ nexty := starty + direction[1 ]
473+
474+ if nextx < 0 || nextx >= len (grid) || nexty < 0 || nexty >= len (grid[0 ]) {
475+ continue
476+ }
477+
478+ if grid[nextx][nexty] <= grid[startx][starty] && !visited[nextx][nexty] {
479+ hasReachFirst , hasReachSecond := dfs (grid, visited, nextx, nexty)
480+ if !canReachFirst {
481+ canReachFirst = hasReachFirst
482+ }
483+ if !canReachSecond {
484+ canReachSecond = hasReachSecond
485+ }
486+ }
487+ }
488+ return canReachFirst, canReachSecond
489+ }
490+ ```
416491
417492### Rust
418493
0 commit comments