SDE & MLE Prep

200. Number of Islands

Problem

In a grid of '1' (land) and '0' (water), an island is a group of land cells connected horizontally or vertically. Count the islands; everything outside the grid is water.

Example: ["11000","11000","00100","00011"] → 3

Constraints: up to 300 × 300.

Scan the grid; each unvisited 1 starts a new island — flood-fill it (DFS/BFS) to mark the whole island visited.

1 1 0 0 0
1 1 0 0 0      -> 3 islands
0 0 1 0 0
0 0 0 1 1

Complexity: O(R·C).

class Solution:
    def numIslands(self, grid: List[List[str]]) -> int:
        R, C = len(grid), len(grid[0])

        def sink(r, c):
            st = [(r, c)]
            grid[r][c] = "0"
            while st:
                r, c = st.pop()
                for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
                    if 0 <= nr < R and 0 <= nc < C and grid[nr][nc] == "1":
                        grid[nr][nc] = "0"
                        st.append((nr, nc))

        count = 0
        for r in range(R):
            for c in range(C):
                if grid[r][c] == "1":
                    count += 1
                    sink(r, c)
        return count