Why it works
- explore adds to seen every land cell it can reach by sides, in any direction, up included. So one call covers a whole island, however it bends.
- The scan starts a new island only at land that is not in seen yet, so each island is counted once: at its first cell in row-by-row order.
- Each land cell goes into seen once and explore runs on it once, so the walk never loops.
Complexity
Time O(rows × cols): each cell is scanned once and each land cell explored once. Memory O(rows × cols) for seen and, at worst, for a call stack as deep as one long island.
nextNow solve it yourself, no hints.
Solve on LeetCode ↗