nathanwailes

LeetCode 200 - Number of Islands - 2022.12.24 solution

Dec 24th, 2022
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.90 KB | None | 0 0
  1. class Solution:
  2.     def numIslands(self, grid: List[List[str]]) -> int:
  3.         # How to solve it: iterate through the cells.  If you find a land
  4.         # cell, increment the number of found islands by 1 and then
  5.         # run DFS to find its extent and add those positions to set of
  6.         # already-discovered land.
  7.         ROWS = len(grid)
  8.         COLS = len(grid[0])
  9.         found_land_positions = set()
  10.         number_of_discovered_islands = 0
  11.         found_water_positions = set()
  12.         def find_adjacent_land_positions(y, x):
  13.             neighbors = [
  14.                 [0, 1],
  15.                 [0, -1],
  16.                 [1, 0],
  17.                 [-1, 0],
  18.             ]
  19.             adjacent_positions = [(y + n[0], x + n[1]) for n in neighbors]
  20.             for pos in adjacent_positions:
  21.                 if pos[0] < 0 or pos[0] > ROWS - 1 or \
  22.                    pos[1] < 0 or pos[1] > COLS - 1:
  23.                    continue
  24.                 if (pos[0], pos[1]) in found_land_positions or (pos[0], pos[1]) in found_water_positions:
  25.                     continue
  26.                 if grid[pos[0]][pos[1]] == "0":
  27.                     found_water_positions.add((i, j))
  28.                 if grid[pos[0]][pos[1]] == "1":
  29.                     found_land_positions.add((pos[0], pos[1]))
  30.                     find_adjacent_land_positions(pos[0], pos[1])
  31.  
  32.         i = 0
  33.         while i < len(grid):
  34.             j = 0
  35.             while j < len(grid[0]):
  36.                 if grid[i][j] == "0":
  37.                     found_water_positions.add((i, j))
  38.                 if (i, j) in found_land_positions:
  39.                     pass
  40.                 elif grid[i][j] == "1":
  41.                     number_of_discovered_islands += 1
  42.                     found_land_positions.add((i, j))
  43.                     find_adjacent_land_positions(i, j)
  44.                 j += 1
  45.             i += 1
  46.         return number_of_discovered_islands
  47.  
Advertisement
Add Comment
Please, Sign In to add comment