# 695. Max Area of Island
Question Link is here.
The solution for this problem is quiet obvious, we travel thought each cell in the grid, whenver we encounter a 1, we start DFS for BFS at that point. I implemented the solution using BFS.
class Solution:
def helper(self, x, y, grid):
queue = [(x,y)]
self.visited.add((x,y))
res = 0
while queue:
x, y = queue.pop()
res += 1
for dir in self.directions:
nextX = x + dir[0]
nextY = y + dir[1]
if nextX >= 0 and nextY >= 0 and nextX < self.height and nextY < self.width and grid[nextX][nextY] == 1 and (nextX, nextY) not in self.visited:
queue.append((nextX, nextY))
self.visited.add((nextX,nextY))
return res
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
self.visited = set()
self.height = len(grid)
self.width = len(grid[0])
self.directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
ans = 0
for i in range(self.height):
for j in range(self.width):
if grid[i][j] == 1 and (i,j) not in self.visited:
temp = self.helper(i,j, grid)
ans = max(ans, temp)
return ans