00:00

Problem Statement

Input/Output Examples

Visual Explanation

Each flood fill marks all cells of one island, so the outer scan starts exactly one fill per island and every cell is processed a constant number of times.

Approaches

Both approaches flood-fill each island once. One uses recursion and changes the grid; the other uses a queue and a visited array.

Java Solutions

Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.

Complexity Analysis

Here rows × cols is the grid size. Every cell is visited by the scan and at most once by a flood fill.

Interview Tips and Recommended Approach

  • Ask whether the grid may be modified. If not, use a visited array.
  • Clarify connectivity. With diagonals, the example has 3 islands instead of 4.
  • Mention union-find for grids that receive new land cells over time.
  • Use BFS for huge islands to avoid StackOverflowError.

Recommended Approach: DFS Flood Fill

Why: it is the shortest correct solution and shows the flood-fill pattern used in many grid problems.