From 8887adbb109acd58ac65bea198d1dc287d99db42 Mon Sep 17 00:00:00 2001 From: limuxuale0927 Date: Fri, 14 Jul 2023 21:52:24 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200200.=E5=B2=9B=E5=B1=BF?= =?UTF-8?q?=E6=95=B0=E9=87=8F.=E5=B9=BF=E6=90=9C=E7=89=88.md=20Python3=20?= =?UTF-8?q?=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0200.岛屿数量.广搜版.md | 35 +++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/problems/0200.岛屿数量.广搜版.md b/problems/0200.岛屿数量.广搜版.md index 39af9f50..4a990a44 100644 --- a/problems/0200.岛屿数量.广搜版.md +++ b/problems/0200.岛屿数量.广搜版.md @@ -196,6 +196,41 @@ class Solution { } } ``` + +Python: + +```python +class Solution: + def numIslands(self, grid: List[List[str]]) -> int: + m, n = len(grid), len(grid[0]) + visited = [[False] * n for _ in range(m)] + dirs = [(-1, 0), (0, 1), (1, 0), (0, -1)] # 四个方向 + ans = 0 + + def bfs(x, y): + q = deque() + q.append([x, y]) + visited[x][y] = True + while q: + curx, cury = q.popleft() + for d in dirs: + nextx = curx + d[0] + nexty = cury + d[1] + if nextx < 0 or nextx >= m or nexty < 0 or nexty >= n: # 越界了,直接跳过 + continue + if visited[nextx][nexty] == False and grid[nextx][nexty] == "1": + q.append([nextx, nexty]) + visited[nextx][nexty] = True # 只要加入队列立刻标记 + + for i in range(m): + for j in range(n): + if grid[i][j] == "1" and not visited[i][j]: + ans += 1 # 遇到没访问过的陆地,+1 + bfs(i, j) # 将与其链接的陆地都标记上 true + + return ans +``` +