forked from partho-maple/coding-interview-gym
-
Notifications
You must be signed in to change notification settings - Fork 80
/
Copy path695_Max_Area_of_Island.py
67 lines (57 loc) · 1.97 KB
/
695_Max_Area_of_Island.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
class Solution(object):
def numIslands(self, grid):
"""
:type grid: List[List[str]]
:rtype: int
"""
sizes = []
visited = [[False for value in row] for row in grid]
for i in range(len(grid)):
for j in range(len(grid[i])):
if visited[i][j]:
continue
else:
self.traverseNode(i, j, grid, visited, sizes)
sizes.sort(reverse= False)
if not sizes:
return 0
else:
return sizes[-1]
def traverseNode(self, i, j, grid, visited, sizes):
currentRiverSize = 0
nodesToExplore = [[i, j]]
while len(nodesToExplore):
currentNode = nodesToExplore.pop()
i = currentNode[0]
j = currentNode[1]
if visited[i][j]:
continue
visited[i][j] = True
if grid[i][j] == 0:
continue
currentRiverSize += 1
unvisitedNeighbours = self.getUnvisitedNeighbour(i, j, grid, visited)
for neighbour in unvisitedNeighbours:
nodesToExplore.append(neighbour)
if currentRiverSize > 0:
sizes.append(currentRiverSize)
def getUnvisitedNeighbour(self, i, j, grid, visited):
unvisitedNeighbours = []
if i > 0 and not visited[i - 1][j]:
unvisitedNeighbours.append([i - 1, j])
if i < len(grid) - 1 and not visited[i + 1][j]:
unvisitedNeighbours.append([i + 1, j])
if j > 0 and not visited[i][j - 1]:
unvisitedNeighbours.append([i, j - 1])
if j < len(grid[0]) - 1 and not visited[i][j + 1]:
unvisitedNeighbours.append([i, j + 1])
return unvisitedNeighbours
# Driver code
sol = Solution()
# grid = [[1,1,0,0,0],
# [1,1,0,0,0],
# [0,0,0,1,1],
# [0,0,0,1,1]]
grid = [[0]]
numOfIlands = sol.numIslands(grid)
print("Max Area of Iands: ", numOfIlands)