nathanwailes

LeetCode 200 - Number of Islands - 2022.12.29 solution

Dec 29th, 2022
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.58 KB | None | 0 0
  1. class Solution:
  2.     def numIslands(self, grid: List[List[str]]) -> int:
  3.         """ How to solve it: Iterate through the grid.  When you hit a land cell, if it
  4.        is not in a 'found_land' set, increment a variable tracking the number of found
  5.        islands and then run DFS to add all positions in this island to the found_land
  6.        set.
  7.        """
  8.         found_land = set()
  9.         number_of_islands = 0
  10.         ROWS = len(grid)
  11.         COLS = len(grid[0])
  12.  
  13.         def add_land_neighbors_to_found_land(r, c):
  14.             adjustments = [
  15.                 [0, 1],
  16.                 [0, -1],
  17.                 [1, 0],
  18.                 [-1, 0],
  19.             ]
  20.             neighbors = [(r + a[0], c + a[1]) for a in adjustments]
  21.             for neighbor in neighbors:
  22.                 nr = neighbor[0]
  23.                 nc = neighbor[1]
  24.                 if nr < 0 or nr > ROWS - 1 or \
  25.                    nc < 0 or nc > COLS - 1:
  26.                    continue
  27.                 if (nr, nc) in found_land:
  28.                     continue
  29.                 cell_value = grid[nr][nc]
  30.                 if cell_value == '0':
  31.                     continue
  32.                 else:
  33.                     found_land.add((nr, nc))
  34.                     add_land_neighbors_to_found_land(nr, nc)
  35.  
  36.         for r in range(ROWS):
  37.             for c in range(COLS):
  38.                 if (r, c) not in found_land and grid[r][c] == '1':
  39.                     number_of_islands += 1
  40.                     found_land.add((r, c))
  41.                     add_land_neighbors_to_found_land(r, c)
  42.         return number_of_islands
Advertisement
Add Comment
Please, Sign In to add comment