Skip to content

Commit 5085e78

Browse files
authored
Update 0200.岛屿数量.广搜版.md
Add python solution
1 parent 496f80d commit 5085e78

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

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

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

0 commit comments

Comments
 (0)