Faaez Razeen

Number of Islands

  • 1 min read
  • Graph
  • LC-Medium

3 years ago

Solution

TimeSpaceExplanation
O(mn)O(mn)
def numIslands(self, grid: List[List[str]]) -> int: num_islands = 0 nrows, ncols = len(grid), len(grid[0]) visited = set() def dfs(r, c): if r >= 0 and r < nrows and c >= 0 and c < ncols and grid[r][c] == '1' and (r, c) not in visited: visited.add((r, c)) for dr, dc in [(0, 1), (0, -1), (1, 0), (-1, 0)]: nr, nc = r + dr, c + dc dfs(nr, nc) for r in range(nrows): for c in range(ncols): if grid[r][c] == '1' and (r, c) not in visited: dfs(r, c) num_islands += 1 return num_islands