Skip to content

Instantly share code, notes, and snippets.

@anhqle
Created June 30, 2020 07:11
Show Gist options
  • Save anhqle/0a2555abd218130c38522057444a1cb8 to your computer and use it in GitHub Desktop.
Save anhqle/0a2555abd218130c38522057444a1cb8 to your computer and use it in GitHub Desktop.
Number of islands
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
num_island = 0
queue = deque()
for x in range(len(grid)):
for y in range(len(grid[0])):
if grid[x][y] == "1":
queue.append((x, y))
while queue:
i, j = queue.popleft()
grid[i][j] = None # mark this cell as visited
for (i2, j2) in [(i - 1, j), (i + 1, j),
(i, j - 1), (i, j + 1)]:
if 0 <= i2 < len(grid) and 0 <= j2 < len(grid[0]) and grid[i2][j2] == "1":
queue.append((i2, j2))
num_island += 1
return num_island
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment