![]() |
VOOZH | about |
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.
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.
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:
Number of rectangular islands is 11
Time complexity of this solution is O(M x N).
Auxiliary Space: O(1)