Skip to content

Commit

Permalink
Merge pull request youngyangyang04#2595 from SusanAIFF/master
Browse files Browse the repository at this point in the history
Update 0101.孤岛的总面积.md
  • Loading branch information
youngyangyang04 authored Jun 28, 2024
2 parents bfc1ab5 + 2b6c2b5 commit 7263271
Showing 1 changed file with 50 additions and 1 deletion.
51 changes: 50 additions & 1 deletion problems/kamacoder/0101.孤岛的总面积.md
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,56 @@ int main() {
### Java

### Python

```python
from collections import deque

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

# 定义四个方向、孤岛面积(遍历完边缘后会被重置)
directions = [[0,1], [1,0], [-1,0], [0,-1]]
count = 0

# 广搜
def bfs(r, c):
global count
q = deque()
q.append((r, c))
g[r][c] = 0
count += 1

while q:
r, c = q.popleft()
for di in directions:
next_r = r + di[0]
next_c = c + di[1]
if next_c < 0 or next_c >= m or next_r < 0 or next_r >= n:
continue
if g[next_r][next_c] == 1:
q.append((next_r, next_c))
g[next_r][next_c] = 0
count += 1


for i in range(n):
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)

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

print(count)
```
### Go

### Rust
Expand Down

0 comments on commit 7263271

Please sign in to comment.