Understanding Number of Islands
Count connected groups of land in a rectangular binary grid. Land is 1, water is 0, and only horizontal or vertical neighbors are connected.
How it works
After discovering an island, visit its entire connected component so none of its cells starts another count.
Scan the grid. Each unseen land cell starts one island and an iterative DFS. Mark cells when pushing them to prevent duplicate work.
Try an example
Input: grid = [[1,1,0],[0,1,0],[1,0,1]]
Output: 3
The upper-left cluster and two isolated bottom cells form three islands.
Constraints
- Cells contain 0 or 1.
- Diagonal cells are not connected.
- Visualization limit: 15 × 15 cells; an empty grid returns 0.
Use the simulator
Change the input, then choose Visualize input. Use Next and Previous to inspect each decision, or Play to advance automatically. Compare approaches and their complexity. Choose Try yourself to write JavaScript, select My code and Visualize code to inspect its execution, or Run Tests to check results.
Execution happens in your browser. Drafts are saved locally; avoid entering secrets or sensitive information.