Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update 0101.孤岛的总面积.md #2824

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 60 additions & 7 deletions problems/kamacoder/0101.孤岛的总面积.md
Original file line number Diff line number Diff line change
Expand Up @@ -257,14 +257,62 @@ public class Main {


### Python
#### 深搜版
```python
position = [[1, 0], [0, 1], [-1, 0], [0, -1]]
count = 0

def dfs(grid, x, y):
global count
grid[x][y] = 0
count += 1
for i, j in position:
next_x = x + i
next_y = y + j
if next_x < 0 or next_y < 0 or next_x >= len(grid) or next_y >= len(grid[0]):
continue
if grid[next_x][next_y] == 1:
dfs(grid, next_x, next_y)

n, m = map(int, input().split())

# 邻接矩阵
grid = []
for i in range(n):
grid.append(list(map(int, input().split())))

# 清除边界上的连通分量
for i in range(n):
if grid[i][0] == 1:
dfs(grid, i, 0)
if grid[i][m - 1] == 1:
dfs(grid, i, m - 1)

for j in range(m):
if grid[0][j] == 1:
dfs(grid, 0, j)
if grid[n - 1][j] == 1:
dfs(grid, n - 1, j)

count = 0 # 将count重置为0
# 统计内部所有剩余的连通分量
for i in range(n):
for j in range(m):
if grid[i][j] == 1:
dfs(grid, i, j)

print(count)
```

#### 广搜版
```python
from collections import deque

# 处理输入
n, m = list(map(int, input().strip()))
n, m = list(map(int, input().split()))
g = []
for _ in range(n):
row = list(map(int, input().strip()))
row = list(map(int, input().split()))
g.append(row)

# 定义四个方向、孤岛面积(遍历完边缘后会被重置)
Expand Down Expand Up @@ -293,17 +341,22 @@ def bfs(r, c):


for i in range(n):
if g[i][0] == 1: bfs(i, 0)
if g[i][m-1] == 1: bfs(i, m-1)
if g[i][0] == 1:
bfs(i, 0)
if g[i][m-1] == 1:
bfs(i, m-1)

for i in range(m):
if g[0][i] == 1: bfs(0, i)
if g[n-1][i] == 1: bfs(n-1, i)
if g[0][i] == 1:
bfs(0, i)
if g[n-1][i] == 1:
bfs(n-1, i)

count = 0
for i in range(n):
for j in range(m):
if g[i][j] == 1: bfs(i, j)
if g[i][j] == 1:
bfs(i, j)

print(count)
```
Expand Down