Skip to content

Commit 49a3552

Browse files
Saw the idea for the solution, leetcode accepted
1 parent 93f258f commit 49a3552

1 file changed

Lines changed: 83 additions & 0 deletions

File tree

Making A Large Island.py

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
# Making A Large Island
2+
# https://leetcode.com/problems/making-a-large-island/
3+
4+
class Solution(object):
5+
def __init__(self):
6+
# key = groupId, val = size
7+
self.groupIndex = {}
8+
9+
def isValid(self, row, col, grid):
10+
if(row >= 0 and row < len(grid)):
11+
if (col >= 0 and col < len(grid[0])):
12+
return True
13+
return False
14+
15+
def getNextMove(self, row, col, grid):
16+
moves = [[-1, 0], [1, 0], [0, -1], [0, 1]]
17+
validMoves = []
18+
for m in moves:
19+
newR = row + m[0]
20+
newC = col + m[1]
21+
if(self.isValid(newR, newC, grid)):
22+
validMoves.append([newR, newC])
23+
return validMoves
24+
25+
def dfs(self, row, col, grid, ID, size):
26+
# mark current visited by changing it to ID
27+
grid[row][col] = ID
28+
# increment the size
29+
size[0] = size[0] + 1
30+
# get next moves
31+
moves = self.getNextMove(row, col, grid)
32+
for m in moves:
33+
if (grid[m[0]][m[1]] == 1):
34+
self.dfs(m[0], m[1], grid, ID, size)
35+
36+
def assignIndex(self, grid):
37+
# random ID
38+
ID = 2
39+
for row in range(len(grid)):
40+
for col in range(len(grid[0])):
41+
if (grid[row][col] == 1):
42+
# start assigning it Id and calculate it's size
43+
size = [0]
44+
self.dfs(row, col, grid, ID, size)
45+
# add it to hash
46+
self.groupIndex[ID] = size[0]
47+
# increment the ID to make it unique for next group
48+
ID = ID + 1
49+
50+
51+
def largestIsland(self, grid):
52+
self.assignIndex(grid)
53+
print grid
54+
maxArea = 0
55+
# for every 0 check up down left right for it's adjacent islands
56+
for row in range(len(grid)):
57+
for col in range(len(grid[0])):
58+
if (grid[row][col] == 0):
59+
currArea = 0
60+
# set variable to keep track of all the island groups we have seen so far
61+
visitedID = set()
62+
# get the next valid neighbors
63+
neighbors = self.getNextMove(row, col, grid)
64+
# for all the neighbors
65+
for n in neighbors:
66+
currID = grid[n[0]][n[1]]
67+
if (currID != 0 and (currID not in visitedID)):
68+
currArea = currArea + self.groupIndex[currID]
69+
visitedID.add(currID)
70+
# add 1 for current cell
71+
currArea = currArea + 1
72+
# compare with maxArea
73+
maxArea = max(maxArea, currArea)
74+
# get max value from hash table
75+
maxAreaFromHashTable = 0
76+
if(self.groupIndex):
77+
maxAreaFromHashTable = max(self.groupIndex.values())
78+
return max(maxAreaFromHashTable, maxArea)
79+
"""
80+
:type grid: List[List[int]]
81+
:rtype: int
82+
"""
83+

0 commit comments

Comments
 (0)