All Problems
#8 medium graphs

Number of Islands

Given an m x n 2D binary grid 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.

Example 1
Input:  grid = [["1","1","1","1","0"],["1","1","0","1","0"],["1","1","0","0","0"],["0","0","0","0","0"]]
Output: 1
Example 2
Input:  grid = [["1","1","0","0","0"],["1","1","0","0","0"],["0","0","1","0","0"],["0","0","0","1","1"]]
Output: 3
Constraints:
1 <= m, n <= 300 grid[i][j] is "0" or "1".
Hint 1: Use DFS or BFS — when you find a land cell, flood-fill all connected land cells and count that as one island.
Hint 2: Mark visited cells to avoid counting them again (e.g. change "1" to "0").
Run your code to see AI analysis