mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
feat: 圖論101孤島总面积 ,新增python深搜算法
This commit is contained in:
@ -307,6 +307,71 @@ for i in range(n):
|
|||||||
|
|
||||||
print(count)
|
print(count)
|
||||||
```
|
```
|
||||||
|
|
||||||
|
```python
|
||||||
|
direction = [[1, 0], [-1, 0], [0, 1], [0, -1]]
|
||||||
|
result = 0
|
||||||
|
|
||||||
|
# 深度搜尋
|
||||||
|
def dfs(grid, y, x):
|
||||||
|
grid[y][x] = 0
|
||||||
|
global result
|
||||||
|
result += 1
|
||||||
|
|
||||||
|
for i, j in direction:
|
||||||
|
next_x = x + j
|
||||||
|
next_y = y + i
|
||||||
|
if (next_x < 0 or next_y < 0 or
|
||||||
|
next_x >= len(grid[0]) or next_y >= len(grid)
|
||||||
|
):
|
||||||
|
continue
|
||||||
|
if grid[next_y][next_x] == 1 and not visited[next_y][next_x]:
|
||||||
|
visited[next_y][next_x] = True
|
||||||
|
dfs(grid, next_y, next_x)
|
||||||
|
|
||||||
|
|
||||||
|
# 讀取輸入值
|
||||||
|
n, m = map(int, input().split())
|
||||||
|
grid = []
|
||||||
|
visited = [[False] * m for _ in range(n)]
|
||||||
|
|
||||||
|
for i in range(n):
|
||||||
|
grid.append(list(map(int, input().split())))
|
||||||
|
|
||||||
|
# 處理邊界
|
||||||
|
for j in range(m):
|
||||||
|
# 上邊界
|
||||||
|
if grid[0][j] == 1 and not visited[0][j]:
|
||||||
|
visited[0][j] = True
|
||||||
|
dfs(grid, 0, j)
|
||||||
|
# 下邊界
|
||||||
|
if grid[n - 1][j] == 1 and not visited[n - 1][j]:
|
||||||
|
visited[n - 1][j] = True
|
||||||
|
dfs(grid, n - 1, j)
|
||||||
|
|
||||||
|
for i in range(n):
|
||||||
|
# 左邊界
|
||||||
|
if grid[i][0] == 1 and not visited[i][0]:
|
||||||
|
visited[i][0] = True
|
||||||
|
dfs(grid, i, 0)
|
||||||
|
# 右邊界
|
||||||
|
if grid[i][m - 1] == 1 and not visited[i][m - 1]:
|
||||||
|
visited[i][m - 1] = True
|
||||||
|
dfs(grid, i, m - 1)
|
||||||
|
|
||||||
|
# 計算孤島總面積
|
||||||
|
result = 0 # 初始化,避免使用到處理邊界時所產生的累加值
|
||||||
|
|
||||||
|
for i in range(n):
|
||||||
|
for j in range(m):
|
||||||
|
if grid[i][j] == 1 and not visited[i][j]:
|
||||||
|
visited[i][j] = True
|
||||||
|
dfs(grid, i, j)
|
||||||
|
|
||||||
|
# 輸出孤島的總面積
|
||||||
|
print(result)
|
||||||
|
```
|
||||||
|
|
||||||
### Go
|
### Go
|
||||||
|
|
||||||
``` go
|
``` go
|
||||||
|
Reference in New Issue
Block a user