Skip to content

Commit 836989f

Browse files
committed
Matrix-Graphs -hard- making a large island by merging islands implementation
1 parent c2c023e commit 836989f

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

Diff for: matrix/hard/making_a_large_island.py

+53
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
from typing import List
2+
3+
4+
class Solution:
5+
def largestIsland(self, grid: List[List[int]]) -> int:
6+
rows = len(grid)
7+
cols = len(grid[0])
8+
visited = []
9+
for i in range(rows):
10+
visited.append([0] * cols)
11+
12+
island_colors = 0
13+
island_sizes = {}
14+
island_sizes[island_colors] = 0
15+
16+
def flood_fill(x, y, color):
17+
grid[x][y] = color
18+
visited[x][y] = 1
19+
island_sizes[color] += 1
20+
coordinates = [(-1, 0), (0, 1), (1, 0), (0, -1)]
21+
for dx, dy in coordinates:
22+
new_x = x + dx
23+
new_y = y + dy
24+
if 0 <= new_x < rows and 0 <= new_y < cols:
25+
if grid[new_x][new_y] == 1 and visited[new_x][new_y] == 0:
26+
flood_fill(new_x, new_y, color)
27+
28+
for i in range(rows):
29+
for j in range(cols):
30+
if grid[i][j] == 1 and visited[i][j] == 0:
31+
island_colors += 1
32+
island_sizes[island_colors] = 0
33+
flood_fill(i, j, island_colors)
34+
35+
max_island_size = max(island_sizes.values())
36+
37+
for ii in range(rows):
38+
for jj in range(cols):
39+
if grid[ii][jj] == 0:
40+
coordinates = [(-1, 0), (0, 1), (1, 0), (0, -1)]
41+
nei_set = set()
42+
for dx, dy in coordinates:
43+
new_i = ii + dx
44+
new_j = jj + dy
45+
if 0 <= new_i < rows and 0 <= new_j < cols:
46+
nei_set.add(grid[new_i][new_j])
47+
48+
this_island_size = 1
49+
for color in nei_set:
50+
this_island_size += island_sizes[color]
51+
52+
max_island_size = max(max_island_size, this_island_size)
53+
return max_island_size

0 commit comments

Comments
 (0)