Skip to content

Commit 3b00f02

Browse files
committed
827
1 parent c7edc19 commit 3b00f02

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

DFS/traditionalDFS/827.md

+60
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
## Making A Large Island
2+
3+
#### Description
4+
5+
[link](https://leetcode.com/problems/making-a-large-island/)
6+
7+
---
8+
9+
#### Solution
10+
11+
- See Code
12+
13+
---
14+
15+
#### Code
16+
17+
> 最坏情况:O(n^2)
18+
19+
```python
20+
class Solution:
21+
'''
22+
思路:
23+
1. 使用index来表示不同的island
24+
2. 更改grid当中表示陆地的值为对应的index
25+
3. 先将所有的island面积计算出来,同时保存在对应index的面积中
26+
4. 遍历0的值,计算能够连接起来的最大值即可
27+
'''
28+
def largestIsland(self, grid: List[List[int]]) -> int:
29+
N = len(grid)
30+
def move(x, y):
31+
for i, j in ((1, 0), (-1, 0), (0, 1), (0, -1)):
32+
if 0 <= x + i < N and 0 <= y + j < N:
33+
yield x + i, y + j
34+
35+
def dfs(x, y, index):
36+
area = 0
37+
grid[x][y] = index
38+
for i, j in move(x, y):
39+
if grid[i][j] == 1:
40+
area += dfs(i, j, index)
41+
return area + 1
42+
43+
# DFS every island and give it an index of island
44+
index = 2
45+
area = {}
46+
for x in range(N):
47+
for y in range(N):
48+
if grid[x][y] == 1:
49+
area[index] = dfs(x, y, index)
50+
index += 1
51+
52+
# traverse every 0 cell and count biggest island it can conntect
53+
res = max(area.values() or [0])
54+
for x in range(N):
55+
for y in range(N):
56+
if grid[x][y] == 0:
57+
possible = set(grid[i][j] for i, j in move(x, y) if grid[i][j] > 1)
58+
res = max(res, sum(area[index] for index in possible) + 1)
59+
return res
60+
```

0 commit comments

Comments
 (0)