![]() |
VOOZH | about |
Given an N*M matrix containing only 0s and 1s, the task is to count the number of square submatrices containing all 1s.
Examples:
Input: arr[][] = {{0, 1, 1, 1},
{1, 1, 1, 1},
{0, 1, 1, 1}}
Output: 15
Explanation:
There are 10 squares of side length 1.
There are 4 squares of side length 2.
There is 1 square of side length 3.
Total number of squares = 10 + 4 + 1 = 15.Input: arr[][] = {{1, 1},
{1, 1},
{1, 1}}
Output: 8
There are 6 squares of length 1
There are 2 squares of length 2
Input: arr[][] = {{1, 0, 1},
{1, 1, 0},
{1, 1, 0}}
Output: 7
How do we compute total numbers of squares that have arr[i][j] as the top left.
7
Time Complexity: Exponential
There are overlapping subproblems as we make three calls for adjacent cells of every cell. So we can optimize the recursive solution. We make a 2D memo array to store the results of already computed subptoblems. We make it 2D because there are two parameters (i and j) that change in recursion. We make the size of memo as m x n because these parameters range from 0 to m-1 and 0 to n-1 respectively. We initialize the memo array as -1 to indiciate nothing is computed and before making a recursive call, we check if the value for the current position is already present in the memo.. If so, it directly returns that value instead of recomputing it.
7
Time Complexity: O(m x n)
Auxiliary Space: O(1)
This problem can be solved using Dynamic Programming.
Below is the implementation of the above approach:
7
Time Complexity: O(m x n)
Auxiliary Space: O(1)