Number of Islands

Problem Description

Given an m x n 2D binary grid of '1' (land) and '0' (water), return the number of islands. An island is surrounded by water and 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 DE Shaw Tier 2 — LC 200. Optimal: DFS/BFS O(m*n). When you find a '1', flood-fill it to '0' (mark visited) and increment count. BFS variant useful for shortest path extensions.

Example Test Cases

Example 1
Input: [[["1","1","1","1","0"],["1","1","0","1","0"],["1","1","0","0","0"],["0","0","0","0","0"]]]
Expected: 1
Example 2
Input: [[["1","1","0","0","0"],["1","1","0","0","0"],["0","0","1","0","0"],["0","0","0","1","1"]]]
Expected: 3
Example 3
Input: [[["1"]]]
Expected: 1

Run your code to see the results