LeetCode Solution 200 - Number of Islands

Problem Statement:

Given an m x n grid consisting 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 surrounded by water.

Example:

Input:

grid = [
  ["1","1","0","0","0"],
  ["1","1","0","0","0"],
  ["0","0","1","0","0"],
  ["0","0","0","1","1"]
]

Output: 3


Optimal Approach: DFS (Depth First Search)

Approach Explanation:

  • Use DFS to explore and mark all connected land cells.
  • Iterate through the grid and count the number of DFS calls (each indicating a new island).
  • Modify the grid in place to avoid extra space usage.

C++ Solution:

class Solution {
public:
    void dfs(vector<vector<char>>& grid, int r, int c) {
        int m = grid.size(), n = grid[0].size();
        if (r < 0 || c < 0 || r >= m || c >= n || grid[r][c] == '0') return;
        grid[r][c] = '0'; // Mark as visited
        vector<int> dir = {-1, 0, 1, 0, -1};
        for (int i = 0; i < 4; ++i) {
            dfs(grid, r + dir[i], c + dir[i + 1]);
        }
    }
    
    int numIslands(vector<vector<char>>& grid) {
        if (grid.empty()) return 0;
        int m = grid.size(), n = grid[0].size(), count = 0;
        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                if (grid[i][j] == '1') {
                    ++count;
                    dfs(grid, i, j);
                }
            }
        }
        return count;
    }
};

Step-by-Step Execution:

  1. Initialization: Iterate over each cell in the grid.
  2. DFS Traversal: If a '1' (land) is found, perform DFS to mark all connected lands as visited.
  3. Counting Islands: Increase the count for each DFS call initiated from an unvisited '1'.
  4. Return the Count: The total number of DFS calls represents the number of islands.

Alternative Approaches & Why Not?

Approach Time Complexity Space Complexity Drawback
Brute Force O(m * n * (m + n)) O(m * n) Inefficient for large grids
BFS (Iterative) O(m * n) O(m * n) Similar complexity, but queue overhead
Union-Find (Disjoint Set) O(m * n) O(m * n) Complex implementation

Why DFS is the Best?

  • DFS is efficient with O(m * n) complexity.
  • In-place modification avoids extra space usage.
  • Simple and easy-to-implement approach.

Complexity Analysis:

  • Time Complexity: O(m * n), as each cell is visited once.
  • Space Complexity: O(m * n) for recursive stack space (in worst-case scenarios).

Conclusion:

This solution efficiently finds the number of islands using DFS, making it optimal for large grids.

No comments:

Post a Comment

Categories

Text Widget

LeetCode & Interview Preparation - A roadmap, problem-solving strategies, or optimized solutions?

Pages

Blog Archive

About Me

My photo
I’m a software developer exploring the depths of .NET, AWS, Angular, React, and digital entrepreneurship. Here, I decode complex problems, share insightful solutions, and navigate the evolving landscape of tech and finance.

Search This Blog

2025 @ayodhyya.com all rights reserved.. Powered by Blogger.

LeetCode Solution 268 - Missing Number

Problem Statement Given an array nums containing n distinct numbers in the range [0, n] , return the only number in the range that is mis...