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

Commit bf0309f

Browse files
Merge pull request youngyangyang04#2824 from miaoxu404/master
Update 0101.孤岛的总面积.md
2 parents 66947ee + 57cec75 commit bf0309f

File tree

1 file changed

+58
-5
lines changed

1 file changed

+58
-5
lines changed

‎problems/kamacoder/0101.孤岛的总面积.md

Lines changed: 58 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -257,6 +257,54 @@ public class Main {
257257

258258

259259
### Python
260+
#### 深搜版
261+
```python
262+
position = [[1, 0], [0, 1], [-1, 0], [0, -1]]
263+
count = 0
264+
265+
def dfs(grid, x, y):
266+
global count
267+
grid[x][y] = 0
268+
count += 1
269+
for i, j in position:
270+
next_x = x + i
271+
next_y = y + j
272+
if next_x < 0 or next_y < 0 or next_x >= len(grid) or next_y >= len(grid[0]):
273+
continue
274+
if grid[next_x][next_y] == 1:
275+
dfs(grid, next_x, next_y)
276+
277+
n, m = map(int, input().split())
278+
279+
# 邻接矩阵
280+
grid = []
281+
for i in range(n):
282+
grid.append(list(map(int, input().split())))
283+
284+
# 清除边界上的连通分量
285+
for i in range(n):
286+
if grid[i][0] == 1:
287+
dfs(grid, i, 0)
288+
if grid[i][m - 1] == 1:
289+
dfs(grid, i, m - 1)
290+
291+
for j in range(m):
292+
if grid[0][j] == 1:
293+
dfs(grid, 0, j)
294+
if grid[n - 1][j] == 1:
295+
dfs(grid, n - 1, j)
296+
297+
count = 0 # 将count重置为0
298+
# 统计内部所有剩余的连通分量
299+
for i in range(n):
300+
for j in range(m):
301+
if grid[i][j] == 1:
302+
dfs(grid, i, j)
303+
304+
print(count)
305+
```
306+
307+
#### 广搜版
260308
```python
261309
from collections import deque
262310

@@ -293,17 +341,22 @@ def bfs(r, c):
293341

294342

295343
for i in range(n):
296-
if g[i][0] == 1: bfs(i, 0)
297-
if g[i][m-1] == 1: bfs(i, m-1)
344+
if g[i][0] == 1:
345+
bfs(i, 0)
346+
if g[i][m-1] == 1:
347+
bfs(i, m-1)
298348

299349
for i in range(m):
300-
if g[0][i] == 1: bfs(0, i)
301-
if g[n-1][i] == 1: bfs(n-1, i)
350+
if g[0][i] == 1:
351+
bfs(0, i)
352+
if g[n-1][i] == 1:
353+
bfs(n-1, i)
302354

303355
count = 0
304356
for i in range(n):
305357
for j in range(m):
306-
if g[i][j] == 1: bfs(i, j)
358+
if g[i][j] == 1:
359+
bfs(i, j)
307360

308361
print(count)
309362
```

0 commit comments

Comments
(0)

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