添加 0200.岛屿数量.广搜版.md Python3 版本

This commit is contained in:
limuxuale0927
2023-07-14 21:52:24 +08:00
parent 9c9ba938f2
commit 8887adbb10

View File

@ -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
```
<p align="center">
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>