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 28d6316

Browse files
🐱(dfs): 695. 岛屿的最大面积
1 parent f6cc021 commit 28d6316

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

‎docs/algorithm/research/dfs/README.md‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,4 +117,41 @@ class Solution(object):
117117
return
118118
for i in xrange(index, len(nums)):
119119
self.dfs(target - nums[i], i + 1, tmp_list + [nums[i]], res, nums)
120+
```
121+
122+
## 695. 岛屿的最大面积
123+
124+
[原题链接](https://leetcode-cn.com/problems/max-area-of-island/)
125+
126+
### 深度优先搜索
127+
128+
设计一个递归函数:输入坐标 `(i, j)`,返回该位置能构成岛屿的最大面积。
129+
130+
- 如果该位置不是岛屿,返回 0
131+
- 如果该位置是岛屿,计算其上下左右位置的面积并相加(此过程不断递归)
132+
133+
```python
134+
class Solution:
135+
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
136+
res = 0
137+
for i in range(len(grid)):
138+
for j in range(len(grid[0])):
139+
res = max(self.dfs(grid, i, j), res)
140+
return res
141+
142+
def dfs(self, grid, i, j):
143+
"""
144+
返回面积
145+
"""
146+
if i < 0 or j < 0 or i >= len(grid) or j >= len(grid[0]) or grid[i][j] != 1:
147+
return 0
148+
# 避免重复计算
149+
grid[i][j] = 0
150+
# 是岛屿,面积为 1
151+
ans = 1
152+
# 四个方向
153+
for di, dj in [[0, -1], [0, 1], [-1, 0], [1, 0]]:
154+
# 计算四个方向总面积
155+
ans += self.dfs(grid, i + di, j + dj)
156+
return ans
120157
```

0 commit comments

Comments
(0)

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