From 947424d311d767dec59f5820b9a83f51da5c2bcc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=99=B6=E7=AC=9B?= <128707187+catherinexrk@users.noreply.github.com> Date: Tue, 12 Nov 2024 10:52:30 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200103.=E6=B0=B4=E6=B5=81?= =?UTF-8?q?=E9=97=AE=E9=A2=98.=20Go=E8=AF=AD=E8=A8=80=20DFS=E7=89=88?= =?UTF-8?q?=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...64\346\265\201\351\227\256\351\242\230.md" | 75 +++++++++++++++++++ 1 file changed, 75 insertions(+) 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 9a34bf094f..65d36e480a 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