Created
June 30, 2020 07:11
-
-
Save anhqle/0a2555abd218130c38522057444a1cb8 to your computer and use it in GitHub Desktop.
Number of islands
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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