Given an n Γ m grid[][] consisting of 'L' (land) and 'W' (water), we need to count the total number of islands present in the grid without modifying the original grid. An island is defined as a group of connected 'L' cells that are adjacent horizontally, vertically, or diagonally, and surrounded by water or the boundary of the grid.
[Approach 1] Using DFS and Additional Matrix - O(n*m) Time and O(n*m) Space
The main idea is to explore each land cell ('L') using DFS and mark all connected land cells that belong to the same island. To avoid modifying the original grid, we maintain a separate visited matrix that keeps track of which cells have already been explored. The DFS explores all 8 possible directions (up, down, left, right, and 4 diagonals), marking every connected 'L' cell as visited. This ensures that all parts of the current island are counted once. Each time we encounter an unvisited land cell, it represents the start of a new island, and we perform DFS to mark all cells of that island. By the end, the total count represents the number of distinct islands in the grid.
Output
4
[Approach 2]Using Breadth First Search - O(n*m) time and O(n*m) space
The idea is to use Breadth First Search(BFS) to explore all connected land cells for each island. We traverse the entire grid, and whenever we encounter an unvisited land cell ('L'), we perform a BFS starting from that cell to explore its entire connected component. During BFS, we visit all cells connected horizontally, vertically, or diagonally to the current land cell. To ensure we donβt revisit the same cell multiple times, we maintain a separate boolean matrix to mark visited cells instead of modifying the original grid. Each BFS traversal explores one complete island, after which we increment the island counter. Repeating this for all cells ensures that every island is counted exactly once, and the final counter gives the total number of islands in the grid.
Output
4
[Approach 3] Using Disjoint Set - O(n*m) time and O(n*m) space
The idea is to model the grid as a graph where each land cell acts as a node. Using the Disjoint Set (Union-Find) structure, we initially treat every land cell as its own parent. Then, for each land cell, we check all eight neighboring directions β if a neighbor is also land, we perform a union operation to merge their sets. After all unions are done, each unique parent in the Disjoint Set represents one distinct island. Counting these unique parents gives the total number of islands in the grid.