diff --git "a/problems/kamacoder/0103.\346\260\264\346\265\201\351\227\256\351\242\230.md" "b/problems/kamacoder/0103.\346\260\264\346\265\201\351\227\256\351\242\230.md" index a09bf089ad..3066c99f28 100644 --- "a/problems/kamacoder/0103.\346\260\264\346\265\201\351\227\256\351\242\230.md" +++ "b/problems/kamacoder/0103.\346\260\264\346\265\201\351\227\256\351\242\230.md" @@ -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