Skip to content

Commit

Permalink
Merge pull request youngyangyang04#2824 from miaoxu404/master
Browse files Browse the repository at this point in the history
Update 0101.孤岛的总面积.md
  • Loading branch information
youngyangyang04 authored Dec 17, 2024
2 parents 66947ee + 57cec75 commit bf0309f
Showing 1 changed file with 58 additions and 5 deletions.
63 changes: 58 additions & 5 deletions problems/kamacoder/0101.孤岛的总面积.md
Original file line number Diff line number Diff line change
Expand Up @@ -257,6 +257,54 @@ 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

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

0 comments on commit bf0309f

Please sign in to comment.