Skip to content

Commit 874abc8

Browse files
committed
Add find building
1 parent e73b0cd commit 874abc8

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

2024/meta/prep.py

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1291,3 +1291,52 @@ def findBuildings(self, heights: List[int]) -> List[int]:
12911291
stack.append((height, i))
12921292

12931293
return list(map(lambda x: x[1], stack))
1294+
1295+
############# 827. Making A Large Island ############
1296+
class Solution:
1297+
def largestIsland(self, grid: List[List[int]]) -> int:
1298+
n = len(grid)
1299+
1300+
# Helper function to perform DFS and mark the islands with their area
1301+
def dfs(x, y, index):
1302+
# If the cell is out of bounds or is not land, return 0
1303+
if x < 0 or y < 0 or x >= n or y >= n or grid[x][y] != 1:
1304+
return 0
1305+
1306+
# Mark the cell with the index of the current island
1307+
grid[x][y] = index
1308+
1309+
# Explore the 4 directions and sum up the size
1310+
return 1 + dfs(x + 1, y, index) + dfs(x - 1, y, index) + dfs(x, y + 1, index) + dfs(x, y - 1, index)
1311+
1312+
# First pass: mark each island with a unique index and store their sizes
1313+
index = 2 # Start marking from 2 (as grid contains 0s and 1s)
1314+
island_sizes = {0: 0} # Dictionary to hold sizes of islands, initialized with size 0 for water
1315+
for i in range(n):
1316+
for j in range(n):
1317+
if grid[i][j] == 1:
1318+
# Perform DFS and calculate the size of the island
1319+
island_size = dfs(i, j, index)
1320+
island_sizes[index] = island_size
1321+
index += 1
1322+
1323+
# Second pass: for each 0, calculate the possible size if we flip it to 1
1324+
max_island = max(island_sizes.values()) # In case the grid is already all land
1325+
directions = [(0, 1), (1, 0), (0, -1), (-1, 0)] # 4 possible directions
1326+
1327+
for i in range(n):
1328+
for j in range(n):
1329+
if grid[i][j] == 0:
1330+
seen = set()
1331+
new_island_size = 1 # Change the 0 to 1 and start with size 1
1332+
for dx, dy in directions:
1333+
ni, nj = i + dx, j + dy
1334+
if 0 <= ni < n and 0 <= nj < n and grid[ni][nj] > 1:
1335+
seen.add(grid[ni][nj])
1336+
1337+
for idx in seen:
1338+
new_island_size += island_sizes[idx]
1339+
1340+
max_island = max(max_island, new_island_size)
1341+
1342+
return max_island

0 commit comments

Comments
 (0)