Skip to content

Commit a433ec1

Browse files
committed
2025-07-12
1 parent b964819 commit a433ec1

1 file changed

Lines changed: 45 additions & 0 deletions

File tree

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
# [LCR 105. 粉刷房子](https://leetcode.cn/problems/ZL6zAn/description/)
2+
3+
> **日期**:2025-07-12
4+
> **所用时间**:10min
5+
6+
## 1. 图的深度优先遍历
7+
8+
本题考查的是图的深度优先遍历(DFS)在网格类问题中的应用。题目要求我们找到二维网格中“岛屿”的最大面积。岛屿由相邻的1组成(上下左右四个方向),面积即为岛屿中1的个数。
9+
10+
### 解题思路
11+
12+
1. **遍历网格**:我们需要遍历整个网格的每一个单元格。
13+
2. **遇到陆地(1)且未访问过时,启动DFS**:每当遇到一个未访问过的1,就以它为起点,进行深度优先遍历,把与它连通的所有1都访问一遍,并统计连通块的面积。
14+
3. **DFS实现**:DFS递归地访问上下左右四个方向的相邻单元格,只要是1且未访问过就继续递归,并累计面积。
15+
4. **记录最大面积**:每次DFS返回的面积与当前最大面积比较,更新最大值。
16+
17+
### 关键细节
18+
19+
- 需要一个`vis`集合或字典来记录哪些格子已经访问过,避免重复遍历。
20+
- 递归时要注意边界条件,防止越界。
21+
- 每次DFS返回的是当前岛屿的面积。
22+
23+
### 复杂度分析
24+
25+
- 时间复杂度: $O(n^2)$
26+
- 空间复杂度: $O(n^2)$
27+
28+
**Python3**
29+
30+
```python
31+
class Solution:
32+
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
33+
m, n = len(grid), len(grid[0])
34+
35+
def dfs(i, j):
36+
if i < 0 or i >= m or j < 0 or j >= n or grid[i][j] == 0:
37+
return 0
38+
grid[i][j] = 0
39+
res = 1
40+
for dx, dy in [(-1, 0), (1, 0), (0, 1), (0, -1)]:
41+
x, y = i + dx, j + dy
42+
res += dfs(x, y)
43+
return res
44+
return max(dfs(i, j) for i in range(m) for j in range(n))
45+
```

0 commit comments

Comments
 (0)