main algorithms/islands.py

18 lines521 B

def islands(grid):
rows, cols = len(grid), len(grid[0])
seen = set()
def sink(r, c):
if not (0 <= r < rows and 0 <= c < cols) or grid[r][c] != "1" or (r, c) in seen:
return
seen.add((r, c))
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
sink(r + dr, c + dc)
count = 0
for r in range(rows):
for c in range(cols):
if grid[r][c] == "1" and (r, c) not in seen:
sink(r, c)
count += 1
return count