Skip to content

Instantly share code, notes, and snippets.

@leticiawanderley
Created June 27, 2021 22:14
Show Gist options
  • Save leticiawanderley/f5fc07ac11cb8f6347a1b5aa91739888 to your computer and use it in GitHub Desktop.
Save leticiawanderley/f5fc07ac11cb8f6347a1b5aa91739888 to your computer and use it in GitHub Desktop.
grid = [
["1","1","1","1","0"],
["1","1","0","1","0"],
["1","1","0","0","0"],
["0","0","0","0","0"]
]
island = 0
seen = set([])
i = 0
while i < len(grid):
j = 0
while j < len(grid[0]):
if (i,j) not in seen and grid[i,j] == '1':
queue = [(i,j)]
while queue:
x, y = queue.pop()
if (x, y) not in seen:
seen.add((x,y))
if x - 1 >= 0 and grid[x-1, y] == '1':
queue.append((x-1, y))
if x < len(grid) and grid[x+1, y] == '1':
queue.append((x+1, y))
if y - 1 >= 0 and grid[x, y-1] == '1':
queue.append((x, y-1))
if y < len(grid[0]) and grid[x, y+1] == '1':
queue.append((x, y+1))
island += 1
j += 1
i += 1
print(island)
[[1]]
[[0]]
[[1,0,0,1]
[0,1,0,0],
[0,1,0,1]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment