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.
Examples
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.
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