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 cells. If you find a land
- # cell, increment the number of found islands by 1 and then
- # run DFS to find its extent and add those positions to set of
- # already-discovered land.
- ROWS = len(grid)
- COLS = len(grid[0])
- found_land_positions = set()
- number_of_discovered_islands = 0
- found_water_positions = set()
- def find_adjacent_land_positions(y, x):
- neighbors = [
- [0, 1],
- [0, -1],
- [1, 0],
- [-1, 0],
- ]
- adjacent_positions = [(y + n[0], x + n[1]) for n in neighbors]
- for pos in adjacent_positions:
- if pos[0] < 0 or pos[0] > ROWS - 1 or \
- pos[1] < 0 or pos[1] > COLS - 1:
- continue
- if (pos[0], pos[1]) in found_land_positions or (pos[0], pos[1]) in found_water_positions:
- continue
- if grid[pos[0]][pos[1]] == "0":
- found_water_positions.add((i, j))
- if grid[pos[0]][pos[1]] == "1":
- found_land_positions.add((pos[0], pos[1]))
- find_adjacent_land_positions(pos[0], pos[1])
- i = 0
- while i < len(grid):
- j = 0
- while j < len(grid[0]):
- if grid[i][j] == "0":
- found_water_positions.add((i, j))
- if (i, j) in found_land_positions:
- pass
- elif grid[i][j] == "1":
- number_of_discovered_islands += 1
- found_land_positions.add((i, j))
- find_adjacent_land_positions(i, j)
- j += 1
- i += 1
- return number_of_discovered_islands
Advertisement
Add Comment
Please, Sign In to add comment