10(July) Largest square formed in a matrix
10. Largest Square Formed in a Matrix
The problem can be found at the following link: Question Link
Problem Description
Given a binary matrix mat of size n * m, find out the maximum length of a side of a square sub-matrix with all 1s.
Example:
Input:
n = 6, m = 5
mat = [[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],
[0, 0, 0, 0, 0]]Output:
3Explanation: The maximum length of a side of the square sub-matrix is 3 where every element is 1.
My Approach
Initialization:
Create a vector
dpof sizemto store the lengths of square sides ending at each column of the current row.Initialize
maxsizeto 0 to keep track of the maximum length of the square sub-matrix found.Use
prevto store the value ofdp[j]from the previous row during the iteration.
Square Calculation:
Iterate through each element of the matrix:
For the first row and the first column, set
dp[j]tomat[i][j].For other elements, if
mat[i][j]is 1, calculate the minimum ofdp[j],dp[j - 1], andprev, then add 1 to get the side length of the square ending atmat[i][j].Update
maxsizeifdp[j]is larger than the currentmaxsize.Update
prevto the value ofdp[j]before the current update.
Return:
Return
maxsize, which is the maximum length of the side of the square sub-matrix with all 1s.
Time and Auxiliary Space Complexity
Expected Time Complexity: O(n * m), as we iterate through each element of the matrix.
Expected Auxiliary Space Complexity: O(m), as we use a vector of size
mto store intermediate results.
Code (C++)
Code (Java)
Code (Python)
Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Let’s make this learning journey more collaborative!
⭐ If you find this helpful, please give this repository a star! ⭐
📍Visitor Count
Last updated