Graph Theory37 sections · 1633 units
Open in Course

Pattern - Grid Components

Connecting pixels

You solved "Number of Islands" with DFS. But DSU works for grids too, especially if you flip pixels from Water to Land dynamically.

Map each cell (r,c)(r, c) to a 1D1D index: id = r * cols + c. Initialize DSU with all land cells. For each land cell, union with adjacent land cells (up, down, left, right).

id := row * numCols + col
if grid[row][col] = Land
    for each neighbor (nr, nc)
        if grid[nr][nc] = Land
            union(id, nr * numCols + nc)

DSU shines when land cells appear one at a time (dynamic connectivity). With DFS, you would need to re-run from scratch each time.