Matrices
Connected Components
200. Number of Islands
Map each cell (row, col) to a flat DSU index via row * n + col. Initialize island_count = 0. Scan left-to-right, top-to-bottom: for every '1' cell, increment island_count. Then union it with any already-seen '1' neighbor above or to the left -- each successful union() returns True (1 in Python), so island_count -= union(...) effectively decrements the count when two previously separate islands merge into one.
- Time
- O(m * n * α(m * n))
- The nested
for row/for colloop visits every one of them * ncells exactly once. - Each
'1'cell makes at most twounioncalls (up, left), each an amortizedα(m * n)with path compression and union by rank -m * n * α(m * n). - Space
- O(m * n)
DisjointSets'sparent,rank, andsizearrays are each sizedn * m.
Component Size
695. Max Area of Island
Map each cell (row, col) to a flat DSU index via row * n + col. Scan left-to-right, top-to-bottom: for every 1 cell, union it with any already-seen 1 neighbor above or to the left. After all unions for that cell, call getSize(idx) -- which does size[find(idx)] -- to read the current component's size. Track the running maximum across all cells.
- Time
- O(m*n*α(m*n))
mandnare the grid's row and column counts. The nestedfor row/for colloops visit each of them*ncells once.- Each
union/findcall (and thegetSizecall, which invokesfindinternally) costsO(α(m*n))amortized with path compression and union by rank. - Space
- O(m*n)
- The DSU's
parent,rank, andsizearrays are each sizedm*n(one entry per cell).