

You are given a square matrix with N rows and N columns, in which each cell (pixel) is either black or white. The black pixels are represented as ‘1’ and the white pixels are represented as ‘0’.
Design an algorithm to find the maximum length of a sub-square of the matrix such that all four borders are filled with black pixels.
The first line of input contains an integer ‘T' representing the number of test cases.
The first line of each test case contains one integer ‘N’ denoting the size of the matrix.
The next ‘N’ lines contain ‘N’ integers separated by spaces describing rows of the matrix. (each element of the matrix is either 0 or 1).
Output Format:
For each test case, on a separate line, output one integer - the maximum length of a side of a subsquare such that all four borders are filled with black pixels.
Note :
You do not need to print anything. It has already been taken care of. Just implement the given function.
1 <= T <= 10
1 <= N <= 10^3
MATRIX[i][j] = 0 or 1
Where ‘T’ is the number of test cases, ‘N’ is the size of the given array, and ‘MATRIX[i][j]’ denotes the j’th element of the i’th row of the matrix "MATRIX".
Time Limit: 1 sec
2
2
1 1
1 1
5
1 1 1 0 0
0 1 1 1 1
0 1 0 1 1
0 1 1 1 1
0 1 1 0 1
2
3
For the first test case, the maximum square submatrix surrounded by all 1’s starts at (0, 0) and ends at (1, 1). And the size of this square matrix is 2.
For the second test case, the maximum square submatrix surrounded by all 1’s starts at (1, 1) and ends at (3, 3). And the size of this square matrix is 3.
2
3
1 0 1
0 1 0
1 0 1
5
1 1 1 0 1
0 0 0 0 0
1 1 0 0 1
1 1 1 0 1
0 0 0 0 0
1
2
Try every possible square submatrix.
The idea is to try every possible square submatrix and check whether all the corner elements are ‘1’. A submatrix is defined by a top left corner (x1, y1) and bottom right corner (x2,y2). Since we are interested in finding a square. If we fix the bottom right corner and fix either the x or the y coordinate of the top left corner, we can calculate the other coordinate using the equation x2 - x1 = y2 - y1.
The algorithm is as follows :
O(N^4), where N is the size of the matrix.
Since, we are fixing 3 coordinates (x2, y2, x1), which is of order N^3, and then checking for the corner elements which are of order N. Hence, the overall time complexity is O(N^4).
O(1).
Since we are using constant extra space.