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 99e85bf

Browse files
committed
feat: 圖論101孤島总面积 ,新增python深搜算法
1 parent 2bac133 commit 99e85bf

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed

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

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -307,6 +307,71 @@ for i in range(n):
307307

308308
print(count)
309309
```
310+
311+
```python
312+
direction = [[1, 0], [-1, 0], [0, 1], [0, -1]]
313+
result = 0
314+
315+
# 深度搜尋
316+
def dfs(grid, y, x):
317+
grid[y][x] = 0
318+
global result
319+
result += 1
320+
321+
for i, j in direction:
322+
next_x = x + j
323+
next_y = y + i
324+
if (next_x < 0 or next_y < 0 or
325+
next_x >= len(grid[0]) or next_y >= len(grid)
326+
):
327+
continue
328+
if grid[next_y][next_x] == 1 and not visited[next_y][next_x]:
329+
visited[next_y][next_x] = True
330+
dfs(grid, next_y, next_x)
331+
332+
333+
# 讀取輸入值
334+
n, m = map(int, input().split())
335+
grid = []
336+
visited = [[False] * m for _ in range(n)]
337+
338+
for i in range(n):
339+
grid.append(list(map(int, input().split())))
340+
341+
# 處理邊界
342+
for j in range(m):
343+
# 上邊界
344+
if grid[0][j] == 1 and not visited[0][j]:
345+
visited[0][j] = True
346+
dfs(grid, 0, j)
347+
# 下邊界
348+
if grid[n - 1][j] == 1 and not visited[n - 1][j]:
349+
visited[n - 1][j] = True
350+
dfs(grid, n - 1, j)
351+
352+
for i in range(n):
353+
# 左邊界
354+
if grid[i][0] == 1 and not visited[i][0]:
355+
visited[i][0] = True
356+
dfs(grid, i, 0)
357+
# 右邊界
358+
if grid[i][m - 1] == 1 and not visited[i][m - 1]:
359+
visited[i][m - 1] = True
360+
dfs(grid, i, m - 1)
361+
362+
# 計算孤島總面積
363+
result = 0 # 初始化,避免使用到處理邊界時所產生的累加值
364+
365+
for i in range(n):
366+
for j in range(m):
367+
if grid[i][j] == 1 and not visited[i][j]:
368+
visited[i][j] = True
369+
dfs(grid, i, j)
370+
371+
# 輸出孤島的總面積
372+
print(result)
373+
```
374+
310375
### Go
311376

312377
``` go

0 commit comments

Comments
(0)

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