This is an interview question: given a boolean matrix find the size of the largest contiguous square sub-matrix, which contains only “true” elements.
I found this question on SO but did not understand the answer. The proposed algorithm moves a diagonal line from the left top to the right bottom and keeps track of the rectangles of “true” elements as the line goes.
My questions:
- How to keep track of the rectangles in the algorithm?
- Why do we move the diagonal line? What if we move a vertical/horizontal line or both?
- How to calculate the algorithm complexity?
I can’t understand the answer in the link you posted, and I don’t think the complexity given there is optimal for your problem. (It claim that there is an
O(N^(3/2)*logN)algorithm whereN=n*nis the number of elements in the original matrix.)For your largest square sub-matrix problem, there is a DP algorithm whose complexity is linear with the number of elements:
Let the original matrix is
A[n][n], we are trying to find a matrixB[n][n], whereB[i][j]indicates the size of largest square sub-matrix whose bottom-right element isA[i][j]. SoAnd the largest B[i][j] is the answer.
p.s. I didn’t check the array range for simplification. You can just consider the out-of-range elements are zero.