LeetCode 筆記 - 695. Max Area of Island

給你一張包含島嶼的海圖,求最大島嶼面積。解題思路聚焦於深度優先搜尋(DFS),當發現陸地時便展開遞迴探索所有相連格位並計數。本文展示如何透過簡單的圖形遍歷技巧,精確衡量複雜形狀島嶼的規模。

發佈
閱讀
約 1 分鐘
字數
280
⚠️ 舊文提醒:本文發佈於約 4 年前,部分內容或指令可能已過時,請斟酌參考。

題目在此 695. Max Area of Island

image 15

給你一張海圖,上邊有島嶼。請計算最大島嶼的面積

解題思維

找到陸地就下去做 Depth First Search 回傳看過的格子數就可以了

程式碼

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
class Solution:
def maxAreaOfIsland(self, g: List[List[int]]) -> int:

size_y = len(g)
size_x = len(g[0])

visited_map = {}

def get_neighers(y, x):

offset = [-1, 1]

result = []
for o in offset:
new_y = y + o
if 0 <= new_y < size_y:
if g[new_y][x] == 1 and (new_y, x) not in visited_map.keys():
result.append((new_y, x))

new_x = x + o
if 0 <= new_x < size_x:
if g[y][new_x] == 1 and (y, new_x) not in visited_map.keys():
result.append((y, new_x))

return result

def dfs(y, x):
if g[y][x] == 0:
return 0
if (y, x) in visited_map.keys():
return 0

visited_map[(y, x)] = 1

neighers = get_neighers(y, x)

result = 0
for n_y, n_x in neighers:
result += dfs(n_y, n_x)

return result + 1

result = 0
for y in range(size_y):
for x in range(size_x):
if g[y][x] == 0:
continue
if (y, x) in visited_map.keys():
continue

result = max(result, dfs(y, x))

return result

也許你也會想看看

輸入關鍵字開始搜尋 · ↑↓ 選擇 · Enter 開啟