From 5db796f3e2643db83e6829a0d7cfb459bb9781b5 Mon Sep 17 00:00:00 2001 From: kimoge <1579457263@qq.com> Date: Wed, 17 Jul 2024 09:53:30 +0800 Subject: [PATCH] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E5=8D=A1=E7=A0=81=E7=BD=9100?= =?UTF-8?q?99.=E5=B2=9B=E5=B1=BF=E7=9A=84=E6=95=B0=E9=87=8F=E6=B7=B1?= =?UTF-8?q?=E6=90=9C=EF=BC=8C=E6=B7=BB=E5=8A=A0Python3=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../kamacoder/0099.岛屿的数量深搜.md | 94 +++++++++++++++++++ 1 file changed, 94 insertions(+) diff --git a/problems/kamacoder/0099.岛屿的数量深搜.md b/problems/kamacoder/0099.岛屿的数量深搜.md index 37f7086a..94ce8d5b 100644 --- a/problems/kamacoder/0099.岛屿的数量深搜.md +++ b/problems/kamacoder/0099.岛屿的数量深搜.md @@ -185,6 +185,100 @@ int main() { ### Python +版本一 + +```python +direction = [[0, 1], [1, 0], [0, -1], [-1, 0]] # 四个方向:上、右、下、左 + + +def dfs(grid, visited, x, y): + """ + 对一块陆地进行深度优先遍历并标记 + """ + for i, j in direction: + next_x = x + i + next_y = y + j + # 下标越界,跳过 + if next_x < 0 or next_x >= len(grid) or next_y < 0 or next_y >= len(grid[0]): + continue + # 未访问的陆地,标记并调用深度优先搜索 + if not visited[next_x][next_y] and grid[next_x][next_y] == 1: + visited[next_x][next_y] = True + dfs(grid, visited, next_x, next_y) + + +if __name__ == '__main__': + # 版本一 + n, m = map(int, input().split()) + + # 邻接矩阵 + grid = [] + for i in range(n): + grid.append(list(map(int, input().split()))) + + # 访问表 + visited = [[False] * m for _ in range(n)] + + res = 0 + for i in range(n): + for j in range(m): + # 判断:如果当前节点是陆地,res+1并标记访问该节点,使用深度搜索标记相邻陆地。 + if grid[i][j] == 1 and not visited[i][j]: + res += 1 + visited[i][j] = True + dfs(grid, visited, i, j) + + print(res) +``` + +版本二 + +```python +direction = [[0, 1], [1, 0], [0, -1], [-1, 0]] # 四个方向:上、右、下、左 + + +def dfs(grid, visited, x, y): + """ + 对一块陆地进行深度优先遍历并标记 + """ + # 与版本一的差别,在调用前增加判断终止条件 + if visited[x][y] or grid[x][y] == 0: + return + visited[x][y] = True + + for i, j in direction: + next_x = x + i + next_y = y + j + # 下标越界,跳过 + if next_x < 0 or next_x >= len(grid) or next_y < 0 or next_y >= len(grid[0]): + continue + # 由于判断条件放在了方法首部,此处直接调用dfs方法 + dfs(grid, visited, next_x, next_y) + + +if __name__ == '__main__': + # 版本二 + n, m = map(int, input().split()) + + # 邻接矩阵 + grid = [] + for i in range(n): + grid.append(list(map(int, input().split()))) + + # 访问表 + visited = [[False] * m for _ in range(n)] + + res = 0 + for i in range(n): + for j in range(m): + # 判断:如果当前节点是陆地,res+1并标记访问该节点,使用深度搜索标记相邻陆地。 + if grid[i][j] == 1 and not visited[i][j]: + res += 1 + dfs(grid, visited, i, j) + + print(res) +``` + ### Go ### Rust