Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution:
- def numIslands(self, grid: List[List[str]]) -> int:
- """ How to solve it: Iterate through the grid. When you hit a land cell, if it
- is not in a 'found_land' set, increment a variable tracking the number of found
- islands and then run DFS to add all positions in this island to the found_land
- set.
- """
- found_land = set()
- number_of_islands = 0
- ROWS = len(grid)
- COLS = len(grid[0])
- def add_land_neighbors_to_found_land(r, c):
- adjustments = [
- [0, 1],
- [0, -1],
- [1, 0],
- [-1, 0],
- ]
- neighbors = [(r + a[0], c + a[1]) for a in adjustments]
- for neighbor in neighbors:
- nr = neighbor[0]
- nc = neighbor[1]
- if nr < 0 or nr > ROWS - 1 or \
- nc < 0 or nc > COLS - 1:
- continue
- if (nr, nc) in found_land:
- continue
- cell_value = grid[nr][nc]
- if cell_value == '0':
- continue
- else:
- found_land.add((nr, nc))
- add_land_neighbors_to_found_land(nr, nc)
- for r in range(ROWS):
- for c in range(COLS):
- if (r, c) not in found_land and grid[r][c] == '1':
- number_of_islands += 1
- found_land.add((r, c))
- add_land_neighbors_to_found_land(r, c)
- return number_of_islands
Advertisement
Add Comment
Please, Sign In to add comment