πDay 5. Find the Number of Islands π§
The problem can be found at the following link: Question Link
π‘ Problem Description:
Given a grid of size n Γ m consisting of 'W' (Water) and 'L' (Land), find the number of islands. An island is formed by connecting adjacent lands in any of the 8 directions (horizontally, vertically, or diagonally) and is surrounded by water or the grid boundary.
π Example Walkthrough:
Example 1:
Input:
grid[][] = [['L', 'L', 'W', 'W', 'W'],
['W', 'L', 'W', 'W', 'L'],
['L', 'W', 'W', 'L', 'L'],
['W', 'W', 'W', 'W', 'W'],
['L', 'W', 'L', 'L', 'W']]Output:
4Explanation: There are 4 distinct islands in the grid.
Example 2:
Input:
Output:
Explanation: There are 2 islands in the grid.
Constraints:
$(1 \leq n, m \leq 500)$
grid[i][j]β {'L','W'}
π― My Approach:
DFS (Recursive Flood Fill β 8 Directions)
We traverse the grid and whenever we find a land cell 'L', we start a DFS flood fill marking all connected lands.
Each such initiation counts as one island.
Algorithm Steps:
Traverse every cell in the grid.
If it's land ('L'), call a recursive DFS function to flood fill all connected lands in 8 directions.
Mark each visited land as
'W'.Count each DFS initiation as a distinct island.
π Time and Auxiliary Space Complexity
Expected Time Complexity: O(n Γ m), as each cell is processed once.
Expected Auxiliary Space Complexity: O(n Γ m) in the worst-case scenario (e.g., when the grid is completely filled with land) due to the recursion stack or BFS/stack storage.
π Solution Code
Code (C++)
Code (Java)
Code (Python)
π― Contribution and Support:
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Letβs make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated