Topic:
Maximal Square
Given a 2D binary matrix filled with 0 's and 1 ' s, find the largest square containing all 1 's and return its area.
Sample Example
For example, given the following matrix:
1 11 1 11 0 0 1 0
Return 4 .
Solving:
Given a two-dimensional 01 matrix, it finds the largest full 1 square and returns its area. The area here is equal to the number of 1 in the square.
Description
1. The 01 matrix columns given are not necessarily equal.
2. The largest square is obviously a combination of many small squares.
Ideas:
The smallest square is the value of this point is 1, the second small square coordinate is:
| (i-1,j-1) |
(I-1,J) |
| (i,j-1) |
(i,j) |
Here, consider the bottom right point is 1, and then consider the other three points of the situation, when the other three points are also 1, the current point (i,j) value plus one, indicating that the formation of the square side length is a (i,j) + 1.
If the small square above is a part of another large square, in judging the large square of the (I,J) point, just consider whether the other three points is zero, non-zero means can form a square, while choosing the three points where the value of the minimum 1 to do me the side length of the large square.
Java Program:
Public classSolution {/** * @parammatrix:a matrix of 0 and 1 *@return: An integer*/ Public intMaxsquare (int[] matrix) { //Write your code here if(matrix==NULL) return0; intm =matrix.length; if(M ==0 ) return0; intn = matrix[0].length; if(n==0 ) return0; intres =-1; for(inti = 1;i<m;i++){ for(intj = 1;j<n;j++){ if(matrix[i][j]!=0) {Matrix[i][j]= Min3 (Matrix[i-1][j-1],matrix[i][j-1],matrix[i-1][j]) + 1; } Res=Math.max (Res,matrix[i][j]); } } returnRes*Res; } Public intMin3 (intAintBintc) {a=Math.min (A, b); C=math.min (A,C); returnC; }}View Code
Total time: 1978 Ms
Python program:
classSolution:#param matrix:a matrix of 0 and 1 #Return:an integer defmaxsquare (self, matrix):#Write your code here ifMatrix = =None:return0 M=len (Matrix)ifm = =0:return0 N=Len (matrix[0])ifn = =0:return0 DP= [[0]*n for_inchrange (m)] ans=0 forIinchRange (m): forJinchrange (N): Dp[i][j]=Matrix[i][j]ifI andJ andDp[i][j]: dp[i][j]= Min (dp[i-1][j],dp[i][j-1],dp[i-1][j-1]) +1ans=Max (Ans,dp[i][j])returnAns*ans
View Code
Lintcode Medium title: Maximal square largest sub-square