Number of Islands

mediumGraphsflood fill DFS/BFS over gridB75Solve on LeetCode#200

Part of Practice: Flood Fill & Regions

You get a grid (up to 300×300) where each cell is "1" (land) or "0" (water). An island is a group of land cells connected up, down, left, or right — diagonals do not count. Everything outside the grid is water. Count how many islands there are.

Examples

Input:
grid = [["1","1","0"],["1","0","0"],["0","0","1"]]
Output:
2

The three land cells in the top-left corner touch each other, forming one island. The land cell at the bottom-right is only diagonally adjacent to nothing else, so it is its own island.

Input:
grid = [["1","1","1"],["0","1","0"],["1","1","1"]]
Output:
1

The middle cell of row 1 bridges the top row and bottom row into a single connected island.

Hints

One at a time — struggle first, peek second.

Your thinking space — verify on LeetCode, then mark it.