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. You may assume all four edges of the grid are all surrounded by water.
Input: grid
Output: 1
Input: grid
Output: 3
m == grid.lengthn == grid[i].length1 <= m, n <= 300grid[i][j] is '0' or '1'.The problem can be effectively solved by considering the grid as a graph. Here each '1' is a land and '0' is water. An island is simply a connected component of '1's, thus our goal is to count these connected components. Depth First Search (DFS) can be used to traverse each island starting from an unexplored piece of land ('1') and marking all the connected lands to avoid multiple counting.
Similar to DFS, the Breadth First Search (BFS) approach is another way to traverse the islands. Instead of traversing deeply through each piece of land, BFS explores all the neighbors of a current land and queues them for further exploration.
This approach uses the Union-Find (Disjoint Set Union) data structure which is optimal when working with connected components problems. Each cell containing a '1' can be initially thought of as its own island, and then we connect lands that are adjacent, effectively reducing the island count when we union two lands.