Maximum size square sub-matrix with all 1s
Maximum size square sub-matrix with all 1s
In maximum size square sub-matrix with all 1s problem, we have to find the largest square matrix with all ones in the given matrix. This article provides a C++ solution with an explanation.
Maximum size square sub-matrix with all 1s Problem Description
Given a r*c matrix with each value as either 0 or 1. Return the side of the largest square sub matrix with all ones.
Input:
- First line contains two integers – the dimension of input matrix (row,col).
- Next r lines contains c integers each – values of each cell of the matrix.
Output:
- Single integer the side of largest square with all 1s.
Example
Input
- 5 5
- 0 1 1 0 1
- 1 1 0 1 0
- 0 1 1 1 0
- 1 1 1 1 0
- 1 1 1 1 1
- 3
- The square from (2,1) to (4,3) is the largest with all 1s.
Maximum size square sub-matrix with all 1s Solution
Brute Force Solution
We will iterate over every possible square sub matrix and check whether that matrix has all 1s or not. The time complexity of just iterating over all squares is O(row*col*max(row,col)) & time complexity of check a square is O(row*col). It is obvious that this solution would timeout.
Dynamic Programming Solution
In this solution we try to think if while checking a particular square if we can reuse previously checked squares.
Algorithm
- Create a dp table of dimension (row,col) where dp[i][j] = side of maximum square possible with bottom right corner at (i,j).
- Now while calculating dp[i][j], our transitions can be –
If(mat[i][j]==0)
dp[i][j] = 0 {as no square is possibl}
else
dp[i][j] = 1 + min(dp[i-1][j-1],dp[i-1][j],dp[i][j-1]) {Taking diagonally upward, left & upward squares.}
- The first row and column of the dp table will act as base case.
- Now just iterate over the table and find the maximum value.
Time Complexity – O(row*col)
Space Complexity – O(row*col)
Code
Output
5 5
0 1 1 0 1
1 1 0 1 0
0 1 1 1 0
1 1 1 1 0
1 1 1 1 1
3
Login/Signup to comment