Skip to content

Commit 0173b76

Browse files
committed
Sync LeetCode submission Runtime - 1458 ms (23.23%), Memory - 30.6 MB (41.88%)
1 parent 23a17bd commit 0173b76

File tree

2 files changed

+78
-0
lines changed

2 files changed

+78
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
<p>You are given an <code>n x n</code> binary matrix <code>grid</code>. You are allowed to change <strong>at most one</strong> <code>0</code> to be <code>1</code>.</p>
2+
3+
<p>Return <em>the size of the largest <strong>island</strong> in</em> <code>grid</code> <em>after applying this operation</em>.</p>
4+
5+
<p>An <strong>island</strong> is a 4-directionally connected group of <code>1</code>s.</p>
6+
7+
<p>&nbsp;</p>
8+
<p><strong class="example">Example 1:</strong></p>
9+
10+
<pre>
11+
<strong>Input:</strong> grid = [[1,0],[0,1]]
12+
<strong>Output:</strong> 3
13+
<strong>Explanation:</strong> Change one 0 to 1 and connect two 1s, then we get an island with area = 3.
14+
</pre>
15+
16+
<p><strong class="example">Example 2:</strong></p>
17+
18+
<pre>
19+
<strong>Input:</strong> grid = [[1,1],[1,0]]
20+
<strong>Output:</strong> 4
21+
<strong>Explanation: </strong>Change the 0 to 1 and make the island bigger, only one island with area = 4.</pre>
22+
23+
<p><strong class="example">Example 3:</strong></p>
24+
25+
<pre>
26+
<strong>Input:</strong> grid = [[1,1],[1,1]]
27+
<strong>Output:</strong> 4
28+
<strong>Explanation:</strong> Can&#39;t change any 0 to 1, only one island with area = 4.
29+
</pre>
30+
31+
<p>&nbsp;</p>
32+
<p><strong>Constraints:</strong></p>
33+
34+
<ul>
35+
<li><code>n == grid.length</code></li>
36+
<li><code>n == grid[i].length</code></li>
37+
<li><code>1 &lt;= n &lt;= 500</code></li>
38+
<li><code>grid[i][j]</code> is either <code>0</code> or <code>1</code>.</li>
39+
</ul>
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
# Approach 2: Component Sizes
2+
3+
# Time: O(n ^ 2)
4+
# Space: O(n ^ 2)
5+
6+
class Solution:
7+
def largestIsland(self, grid: List[List[int]]) -> int:
8+
n = len(grid)
9+
10+
def get_neighbors(r, c):
11+
for nr, nc in ((r - 1, c), (r + 1, c), (r, c - 1), (r, c + 1)):
12+
if 0 <= nr < n and 0 <= nc < n:
13+
yield nr, nc
14+
15+
def dfs(r, c, index):
16+
ans = 1
17+
grid[r][c] = index
18+
for nr, nc in get_neighbors(r, c):
19+
if grid[nr][nc] == 1:
20+
ans += dfs(nr, nc, index)
21+
return ans
22+
23+
area = {}
24+
index = 2
25+
for r in range(n):
26+
for c in range(n):
27+
if grid[r][c] == 1:
28+
area[index] = dfs(r, c, index)
29+
index += 1
30+
31+
ans = max(area.values() or [0])
32+
for r in range(n):
33+
for c in range(n):
34+
if grid[r][c] == 0:
35+
seen = {grid[nr][nc] for nr, nc in get_neighbors(r, c) if grid[nr][nc] > 1}
36+
ans = max(ans, 1 + sum(area[i] for i in seen))
37+
38+
return ans
39+

0 commit comments

Comments
 (0)