Skip to content

Commit 7be0460

Browse files
Merge pull request youngyangyang04#2156 from amcw7777/patch-2
Update 0200.岛屿数量.广搜版.md
2 parents 9c9ba93 + e5d3d11 commit 7be0460

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

problems/0200.岛屿数量.广搜版.md

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -196,7 +196,51 @@ class Solution {
196196
}
197197
}
198198
```
199+
200+
## 其他语言版本
201+
### Python
202+
BFS solution
203+
```python
204+
class Solution:
205+
def __init__(self):
206+
self.dirs = [[0, 1], [1, 0], [-1, 0], [0, -1]]
207+
208+
def numIslands(self, grid: List[List[str]]) -> int:
209+
m = len(grid)
210+
n = len(grid[0])
211+
visited = [[False]*n for _ in range(m)]
212+
res = 0
213+
for i in range(m):
214+
for j in range(n):
215+
if visited[i][j] == False and grid[i][j] == '1':
216+
res += 1
217+
self.bfs(grid, i, j, visited) # Call bfs within this condition
218+
return res
219+
220+
def bfs(self, grid, i, j, visited):
221+
q = deque()
222+
q.append((i,j))
223+
visited[i][j] = True
224+
while q:
225+
x, y = q.popleft()
226+
for k in range(4):
227+
next_i = x + self.dirs[k][0]
228+
next_j = y + self.dirs[k][1]
229+
230+
if next_i < 0 or next_i >= len(grid):
231+
continue
232+
if next_j < 0 or next_j >= len(grid[0]):
233+
continue
234+
if visited[next_i][next_j]:
235+
continue
236+
if grid[next_i][next_j] == '0':
237+
continue
238+
q.append((next_i, next_j))
239+
visited[next_i][next_j] = True
240+
```
241+
199242
<p align="center">
200243
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
201244
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
202245
</a>
246+
```

0 commit comments

Comments
 (0)