VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-number-islands-every-island-separated-line/

⇱ Count number of islands where every island is row-wise and column-wise separated - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count number of islands where every island is row-wise and column-wise separated

Last Updated : 14 Sep, 2023

Given a rectangular matrix which has only two possible values 'X' and 'O'. The values 'X' always appear in form of rectangular islands and these islands are always row-wise and column-wise separated by at least one line of 'O's. Note that islands can only be diagonally adjacent. Count the number of islands in the given matrix. 

Examples:

mat[M][N] = {{'O', 'O', 'O'},
{'X', 'X', 'O'},
{'X', 'X', 'O'},
{'O', 'O', 'X'},
{'O', 'O', 'X'},
{'X', 'X', 'O'}
};
Output: Number of islands is 3
mat[M][N] = {{'X', 'O', 'O', 'O', 'O', 'O'},
{'X', 'O', 'X', 'X', 'X', 'X'},
{'O', 'O', 'O', 'O', 'O', 'O'},
{'X', 'X', 'X', 'O', 'X', 'X'},
{'X', 'X', 'X', 'O', 'X', 'X'},
{'O', 'O', 'O', 'O', 'X', 'X'},
};
Output: Number of islands is 4

We strongly recommend to minimize your browser and try this yourself first.

The idea is to count all top-leftmost corners of given matrix. We can check if a 'X' is top left or not by checking following conditions. 

  1. A 'X' is top of rectangle if the cell just above it is a 'O' 
  2. A 'X' is leftmost of rectangle if the cell just left of it is a 'O'

Note that we must check for both conditions as there may be more than one top cells and more than one leftmost cells in a rectangular island. Below is the implementation of above idea. 


Output
Number of rectangular islands is 3

Time complexity of this solution is O(M x N).
Auxiliary Space: O(1)

To implement this using a dynamic programming (DP) approach, we need to modify the logic of counting islands. Instead of checking each cell individually, we'll maintain a DP table to store the count of islands up to a particular cell.

Here's the modified version of the program using a DP approach:


Output
Number of rectangular islands is 11

Time complexity of this solution is O(M x N).
Auxiliary Space: O(1)

Comment
Article Tags:
Article Tags: