Given a binary matrix, find the size of the largest square submatrix, which is surrounded by all 1’s.

For example, the size of the largest square submatrix in the following binary matrix is 4. The largest square submatrix is formed by cells (0, 2), (3, 2), (0, 5), and (3, 5).

   1    1    1    1    1    1
   1    0    1    1    0    1
   0    1    1    0    0    1
   1    1    1    1    1    1
   1    0    0    1    0    1
   1    0    1    1    0    0
   1    0    1    0    1    1
   1    1    1    0    1    1

Practice this problem

The brute-force solution is to consider every square submatrix and check if it is surrounded by all 1's. We keep track of the dimensions of the largest square submatrix seen and finally return it. The time complexity of this solution is O(M2 × N2), where M and N are dimensions of the matrix.

 
We can reduce the time complexity of the problem to O(M2 × N) by using O(M × N) extra space. The idea is to create two auxiliary matrices, say X and Y, where X[i][j] and Y[i][j] stores the total number of continuous horizontal and vertical 1's ending at cell (i, j), respectively in the given matrix.

After filling both auxiliary matrices, process each cell (i, j) starting from the last cell in the last row. For every cell (i, j), take the minimum of X[i][j] and Y[i][j] which could be the maximum length of the right vertical line and bottom horizontal line of the square matrix ending at cell (i, j). The cell ending at the current cell (i, j) would form a square submatrix if there exist a left vertical line and a top horizontal line of at least the same length. Keep track of the largest square submatrix’s dimensions so far and return it when every cell is processed.

 
Following is the C++, Java, and Python program that demonstrates it:

C++


Download  Run Code

Output:

The largest square submatrix has a length of 4

Java


Download  Run Code

Output:

The largest square submatrix has a length of 4

Python


Download  Run Code

Output:

The largest square submatrix has a length of 4