return The area of the smallest (axis-aligned) Rectangle this encloses all black pixels. For example, given the following image:[ "0010", "0110", "0100"= 0, y = 2 6.
Imagine We project the 2D array to the bottom axis with the rule "if a column have any black pixel it's projection is black otherwise white. " The projected 1D array is "0110"
Theorem
If there is only one black pixel region and then in a projected 1D array all the black pixels is connected.
This means we can does a binary search in each half to find the boundaries, if we know one black pixel ' s position. And we do know that.
To find the left boundary, does the binary search in the range and find the first column vectors who have any [0, y)
black Pixe L.
To determine if a column vector have a black pixel is and the search in total are O(m)
O(m log n)
We can do the same for the other boundaries. The area was then calculated by the boundaries. Thus the algorithm runs inO(m log n + n log m)
1 Public classSolution {2 Public intMinarea (Char[] Image,intXinty) {3 intm =image.length;4 intn = image[0].length;5 intleft =Searchleft (image, y);6 intright =searchright (image, y);7 inttop =searchtop (image, x);8 intBottom =Searchbottom (image, x);9 return(right-left+1) * (bottom-top+1);Ten } One A Public intSearchleft (Char[] Image,intRight ) { - intL = 0, r =Right ; - while(L <=r) { the intm = (l+r)/2; - if(!findblack (image, M,false)) L = m+1; - Elser = M-1; - } + returnl; - } + A Public intSearchright (Char[] Image,intLeft ) { at intL = left, r = image[0].length-1; - while(L <=r) { - intm = (l+r)/2; - if(!findblack (image, M,false)) R = M-1; - ElseL = m+1; - } in returnR; - } to + Public intSearchtop (Char[] Image,intbottom) { - intL = 0, r =Bottom; the while(L <=r) { * intm = (l+r)/2; $ if(!findblack (image, M,true)) L = m+1;Panax Notoginseng Elser = M-1; - } the returnl; + } A the Public intSearchbottom (Char[] Image,inttop) { + intL=top, R=image.length-1; - while(L <=r) { $ intm = (l+r)/2; $ if(!findblack (image, M,true)) R = M-1; - ElseL = m+1; - } the returnR; - }Wuyi the Public BooleanFindblack (Char[] Image,intCurBooleanrow) { - intm =image.length; Wu intn = image[0].length; - if(row) { About for(inti=0; i<n; i++) { $ if(Image[cur][i] = = ' 1 ') - return true; - } - return false; A } + Else { the for(intj=0; j<m; J + +) { - if(Image[j][cur] = = ' 1 ') $ return true; the } the return false; the } the } -}
Leetcode:smallest Rectangle enclosing Black Pixels