Given an m x n 2D binary grid which represents a map of '1's (land) and '0's (water), return the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically.
grid = [["1","1","1","1","0"],["1","1","0","1","0"],["1","1","0","0","0"],["0","0","0","0","0"]]1grid = [["1","1","0","0","0"],["1","1","0","0","0"],["0","0","1","0","0"],["0","0","0","1","1"]]3'0' or '1'grid[r][c] == '1': start DFS, then count++'0' (sunk), recurse on 4 neighborscountWhen we encounter an unvisited land cell, we know it belongs to a new island. By DFS-sinking the entire connected component (marking all reachable '1's as '0'), we ensure no cell of that island is counted again. The number of times we trigger a DFS from the outer loop equals exactly the number of islands — one flood-fill per island.
Counting land cells is not enough, because one island can have many cells. We need to recognise which cells belong together.
Scan the grid cell by cell. When you find land that has not been visited, that is a new island, so add 1. Then flood fill: use DFS to visit every connected land cell, and mark it as water so it is never counted again.
New unvisited land means a new island, then flood fill it. Sinking visited land prevents double counting.
Run the animation above on your own input, or watch the 1:30 video explanation of Number of Islands with a dry run and Java code.