nathanwailes

LeetCode 695 - Max Area of Island - 2022.12.26 solution

Dec 25th, 2022
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.75 KB | None | 0 0
  1. class Solution:
  2.     def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
  3.         # How to solve it: iterate through the cells in the grid, if you find
  4.         # a part of an island that we haven't handled before, run DFS to find
  5.         # all adjacent cells that are part of the same island, adding them to
  6.         # a set of found land.  Have a variable that keeps track of the
  7.         # largest land mass found.
  8.         ROWS = len(grid)
  9.         COLS = len(grid[0])
  10.         land_positions_found = set()
  11.         max_land_area = 0
  12.  
  13.         def get_size_of_island(y, x):
  14.             neighbor_adjustments = [
  15.                 [0, 1],
  16.                 [0, -1],
  17.                 [1, 0],
  18.                 [-1, 0],
  19.             ]
  20.             neighbors = [(y + adj[0], x + adj[1]) for adj in neighbor_adjustments]
  21.             size_of_island = 1
  22.             for neighbor in neighbors:
  23.                 if neighbor[0] < 0 or neighbor[0] > ROWS - 1 or \
  24.                    neighbor[1] < 0 or neighbor[1] > COLS - 1 or \
  25.                    neighbor in land_positions_found:
  26.                    continue
  27.                 if grid[neighbor[0]][neighbor[1]] == 1:
  28.                     land_positions_found.add((neighbor[0], neighbor[1]))
  29.                     size_of_island += get_size_of_island(neighbor[0], neighbor[1])
  30.             return size_of_island
  31.  
  32.  
  33.         i = 0
  34.         while i < ROWS:
  35.             j = 0
  36.             while j < COLS:
  37.                 if (i, j) not in land_positions_found and grid[i][j] == 1:
  38.                     land_positions_found.add((i, j))
  39.                     area_of_island = get_size_of_island(i, j)
  40.                     max_land_area = max(area_of_island, max_land_area)
  41.                 j += 1
  42.             i += 1
  43.         return max_land_area
Advertisement
Add Comment
Please, Sign In to add comment