Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution:
- def numIslands(self, grid: List[List[str]]) -> int:
- if grid is None or len(grid) is 0:
- return 0
- row_count = len(grid)
- col_count = len(grid[0])
- visited = [[0 for _ in range(col_count)] for _ in range(row_count)]
- islands = 0
- for row_idx in range(len(visited)):
- for col_idx in range(len(visited[row_idx])):
- if not visited[row_idx][col_idx]:
- # haven't visited this cell before
- # find current cell in original
- curr_cell = grid[row_idx][col_idx]
- if curr_cell is "1":
- # if 1, new island has been found
- islands += 1
- # now must find all connecting land elements
- lands = [(row_idx, col_idx)]
- while lands:
- curr_land = lands.pop()
- associated_row = curr_land[0]
- associated_col = curr_land[1]
- if grid[associated_row][associated_col] is "1":
- if not visited[associated_row][associated_col]:
- visited[associated_row][associated_col] = 1
- # go through these neighbors and add to lands
- look_up = associated_row - 1
- look_down = associated_row + 1
- look_left = associated_col - 1
- look_right = associated_col + 1
- if look_up >= 0 and look_up < row_count:
- lands.append((look_up, associated_col))
- if look_down >= 0 and look_down < row_count:
- lands.append((look_down, associated_col))
- if look_left >= 0 and look_left < col_count:
- lands.append((associated_row, look_left))
- if look_right >= 0 and look_right < col_count:
- lands.append((associated_row, look_right))
- return islands
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement