Merge pull request #2181 from LIMUXUALE0927/master

添加 0200.岛屿数量.广搜版.md 和 0200.岛屿数量.深搜版.md Python3 版本
This commit is contained in:
程序员Carl
2023-07-31 10:37:18 +08:00
committed by GitHub
2 changed files with 63 additions and 0 deletions

View File

@ -197,6 +197,7 @@ class Solution {
}
```
### Python
BFS solution
```python
@ -236,6 +237,7 @@ class Solution:
continue
q.append((next_i, next_j))
visited[next_i][next_j] = True
```
<p align="center">

View File

@ -218,6 +218,67 @@ 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)] # 四个方向
result = 0
def dfs(x, y):
for d in dirs:
nextx = x + d[0]
nexty = y + d[1]
if nextx < 0 or nextx >= m or nexty < 0 or nexty >= n: # 越界了,直接跳过
continue
if not visited[nextx][nexty] and grid[nextx][nexty] == '1': # 没有访问过的同时是陆地的
visited[nextx][nexty] = True
dfs(nextx, nexty)
for i in range(m):
for j in range(n):
if not visited[i][j] and grid[i][j] == '1':
visited[i][j] = True
result += 1 # 遇到没访问过的陆地,+1
dfs(i, j) # 将与其链接的陆地都标记上 true
return result
```
```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)] # 四个方向
result = 0
def dfs(x, y):
if visited[x][y] or grid[x][y] == '0':
return # 终止条件:访问过的节点 或者 遇到海水
visited[x][y] = True
for d in dirs:
nextx = x + d[0]
nexty = y + d[1]
if nextx < 0 or nextx >= m or nexty < 0 or nexty >= n: # 越界了,直接跳过
continue
dfs(nextx, nexty)
for i in range(m):
for j in range(n):
if not visited[i][j] and grid[i][j] == '1':
result += 1 # 遇到没访问过的陆地,+1
dfs(i, j) # 将与其链接的陆地都标记上 true
return result
```
<p align="center">
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>