Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

[pull] master from youngyangyang04:master #512

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

Merged
pull merged 3 commits into AlgorithmAndLeetCode:master from youngyangyang04:master
Dec 17, 2024
Merged
Changes from 1 commit
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
Next Next commit
Update 0101.孤岛的总面积.md
对101.孤岛的总面积的python解法深搜版的补充,以及对广搜版的部分修改
  • Loading branch information
miaoxu404 committed Nov 6, 2024
commit a4f9f01eb48b2a7d929154be69fd6cfe9dc9ea19
67 changes: 60 additions & 7 deletions problems/kamacoder/0101.孤岛的总面积.md
View file Open in desktop
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

AltStyle によって変換されたページ (->オリジナル) /