Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution:
- def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
- # How to solve it: iterate through the cells in the grid, if you find
- # a part of an island that we haven't handled before, run DFS to find
- # all adjacent cells that are part of the same island, adding them to
- # a set of found land. Have a variable that keeps track of the
- # largest land mass found.
- ROWS = len(grid)
- COLS = len(grid[0])
- land_positions_found = set()
- max_land_area = 0
- def get_size_of_island(y, x):
- neighbor_adjustments = [
- [0, 1],
- [0, -1],
- [1, 0],
- [-1, 0],
- ]
- neighbors = [(y + adj[0], x + adj[1]) for adj in neighbor_adjustments]
- size_of_island = 1
- for neighbor in neighbors:
- if neighbor[0] < 0 or neighbor[0] > ROWS - 1 or \
- neighbor[1] < 0 or neighbor[1] > COLS - 1 or \
- neighbor in land_positions_found:
- continue
- if grid[neighbor[0]][neighbor[1]] == 1:
- land_positions_found.add((neighbor[0], neighbor[1]))
- size_of_island += get_size_of_island(neighbor[0], neighbor[1])
- return size_of_island
- i = 0
- while i < ROWS:
- j = 0
- while j < COLS:
- if (i, j) not in land_positions_found and grid[i][j] == 1:
- land_positions_found.add((i, j))
- area_of_island = get_size_of_island(i, j)
- max_land_area = max(area_of_island, max_land_area)
- j += 1
- i += 1
- return max_land_area
Advertisement
Add Comment
Please, Sign In to add comment