Zero To DSAZero To DSA
Privacy Policy
Clone Graph

Number of Islands

medium
Time: O(m * n)
Space: O(m * n)

Given an m×n 2D binary grid '1' (land) and '0' (water), count the number of islands. An island is surrounded by water and formed by connecting adjacent lands horizontally or vertically.

Constraints

  • m, n <= 300

Examples

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