From 5085e78e601fa6450e80b0d5d9b060df26857dcb Mon Sep 17 00:00:00 2001 From: Leon He Date: Thu, 29 Jun 2023 11:25:27 -0700 Subject: [PATCH 1/2] =?UTF-8?q?Update=200200.=E5=B2=9B=E5=B1=BF=E6=95=B0?= =?UTF-8?q?=E9=87=8F.=E5=B9=BF=E6=90=9C=E7=89=88.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add python solution --- problems/0200.岛屿数量.广搜版.md | 41 +++++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/problems/0200.岛屿数量.广搜版.md b/problems/0200.岛屿数量.广搜版.md index 39af9f50..2bb0973a 100644 --- a/problems/0200.岛屿数量.广搜版.md +++ b/problems/0200.岛屿数量.广搜版.md @@ -200,3 +200,44 @@ class Solution { +``` +### Python +BFS solution +```python +class Solution: + def __init__(self): + self.dirs = [[0, 1], [1, 0], [-1, 0], [0, -1]] + + def numIslands(self, grid: List[List[str]]) -> int: + m = len(grid) + n = len(grid[0]) + visited = [[False]*n for _ in range(m)] + res = 0 + for i in range(m): + for j in range(n): + if visited[i][j] == False and grid[i][j] == '1': + res += 1 + self.bfs(grid, i, j, visited) # Call bfs within this condition + return res + + def bfs(self, grid, i, j, visited): + q = deque() + q.append((i,j)) + visited[i][j] = True + while q: + x, y = q.popleft() + for k in range(4): + next_i = x + self.dirs[k][0] + next_j = y + self.dirs[k][1] + + if next_i < 0 or next_i >= len(grid): + continue + if next_j < 0 or next_j >= len(grid[0]): + continue + if visited[next_i][next_j]: + continue + if grid[next_i][next_j] == '0': + continue + q.append((next_i, next_j)) + visited[next_i][next_j] = True +``` From e5d3d1188555ea83aa00c156afcc249d4fd1fe42 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=A8=8B=E5=BA=8F=E5=91=98Carl?= Date: Sun, 16 Jul 2023 20:39:00 +0800 Subject: [PATCH 2/2] =?UTF-8?q?Update=200200.=E5=B2=9B=E5=B1=BF=E6=95=B0?= =?UTF-8?q?=E9=87=8F.=E5=B9=BF=E6=90=9C=E7=89=88.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0200.岛屿数量.广搜版.md | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/problems/0200.岛屿数量.广搜版.md b/problems/0200.岛屿数量.广搜版.md index 2bb0973a..c20fe4f1 100644 --- a/problems/0200.岛屿数量.广搜版.md +++ b/problems/0200.岛屿数量.广搜版.md @@ -196,11 +196,8 @@ class Solution { } } ``` -

- - - -``` + +## 其他语言版本 ### Python BFS solution ```python @@ -241,3 +238,9 @@ class Solution: q.append((next_i, next_j)) visited[next_i][next_j] = True ``` + +

+ + + +```