Count Sub Islands LeetCode Solution

Count Sub Islands

You are given two m x n binary matrices grid1 and grid2 containing only 0‘s (representing water) and 1‘s (representing land). An island is a group of 1‘s connected 4-directionally (horizontal or vertical). Any cells outside of the grid are considered water cells.

An island in grid2 is considered a sub-island if there is an island in grid1 that contains all the cells that make up this island in grid2.

Return the number of islands in grid2 that are considered sub-islands.

Example 1:

Count Sub Islands LeetCode Solution
Input: grid1 = [[1,1,1,0,0],[0,1,1,1,1],[0,0,0,0,0],[1,0,0,0,0],[1,1,0,1,1]], grid2 = [[1,1,1,0,0],[0,0,1,1,1],[0,1,0,0,0],[1,0,1,1,0],[0,1,0,1,0]]
Output: 3
Explanation: In the picture above, the grid on the left is grid1 and the grid on the right is grid2.
The 1s colored red in grid2 are those considered to be part of a sub-island. There are three sub-islands.

Example 2:

Count Sub Islands LeetCode Solution
Input: grid1 = [[1,0,1,0,1],[1,1,1,1,1],[0,0,0,0,0],[1,1,1,1,1],[1,0,1,0,1]], grid2 = [[0,0,0,0,0],[1,1,1,1,1],[0,1,0,1,0],[0,1,0,1,0],[1,0,0,0,1]]
Output: 2 
Explanation: In the picture above, the grid on the left is grid1 and the grid on the right is grid2.
The 1s colored red in grid2 are those considered to be part of a sub-island. There are two sub-islands.

Constraints:

  • m == grid1.length == grid2.length
  • n == grid1[i].length == grid2[i].length
  • 1 <= m, n <= 500
  • grid1[i][j] and grid2[i][j] are either 0 or 1.

Program:

int solve(vector<vector<int>>& g1, vector<vector<int>>& g2, int i, int j)
    {
        int n = g2.size(), m = g2[0].size();
        
        if(i < 0 || i == n || j <0 || j== m || g2[i][j] == 0)
            return 0;
         
         if(g1[i][j] == 0)
             return -1;
        
        g2[i][j] = 0;
        
        int a = solve(g1, g2, i+1, j);
        int b = solve(g1, g2, i-1, j);
        int c = solve(g1, g2, i, j-1);
        int d = solve(g1, g2, i, j+1);
         
         if(a == -1 || b == -1 || c == -1 || d == -1)
             return -1;
         
         return 1;
         
    }
    int countSubIslands(vector<vector<int>>& g1, vector<vector<int>>& g2) {
        int n = g2.size(), m = g2[0].size(), ans =0;
        
        for(int i=0;i<n;i++)
        {
            for(int j=0;j<m;j++)
            {
                if(g2[i][j] == 1)  {
                    if(solve(g1, g2, i, j) == 1)
                        ans++;
                }
            }
        }
        return ans;
    }

June Long Challenge 2021 Solutions

Leave a Comment