Leetcode 1905: Count Sub Islands

grid47
grid47
Exploring patterns and algorithms
Apr 30, 2024 8 min read

You are given two m x n binary matrices, grid1 and grid2, where each cell can either be 0 (representing water) or 1 (representing land). An island is a group of connected 1’s, connected either horizontally or vertically. An island in grid2 is considered a sub-island if there is a corresponding island in grid1 that contains all the cells of the island in grid2. Your task is to determine the number of sub-islands in grid2.
Problem
Approach
Steps
Complexity
Input: The input consists of two m x n binary matrices grid1 and grid2. Each element in the grid is either 0 or 1.
Example: Example 1: 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]]
Constraints:
• 1 <= m, n <= 500
• grid1 and grid2 have the same dimensions
• grid1[i][j], grid2[i][j] are either 0 or 1
Output: The output should be the number of islands in grid2 that are considered sub-islands.
Example: Example 1: Output: 3
Constraints:
Goal: We need to count the number of sub-islands in grid2 by identifying islands in grid2 that are fully contained within the corresponding islands in grid1.
Steps:
• Iterate over grid2 and for each land cell (1), perform a DFS to find all connected land cells.
• For each island in grid2, check if all its cells are part of an island in grid1.
• Count the number of valid islands that satisfy the sub-island condition.
Goal: The problem requires handling two binary matrices of the same size, where the dimensions can be as large as 500x500.
Steps:
• The grids must have the same dimensions.
• The dimensions of the grid must be within the range 1 <= m, n <= 500.
Assumptions:
• Both grids are binary matrices with 0's and 1's.
• An island is formed by connected 1's in a 4-directional manner.
Input: Example 1: 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]]
Explanation: In grid1, we have several islands formed by connected 1's. In grid2, some of these islands are fully contained within the islands of grid1, making them sub-islands. There are three sub-islands in grid2.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus