原题链接在这里:https://leetcode.com/problems/smallest-rectangle-enclosing-black-pixels/
题目:
An image is represented by a binary matrix with 0
as a white pixel and 1
as a black pixel. The black pixels are connected, i.e., there is only one black region. Pixels are connected horizontally and vertically. Given the location (x, y)
of one of the black pixels, return the area of the smallest (axis-aligned) rectangle that encloses all black pixels.
For example, given the following image:
[ "0010", "0110", "0100" ]
and x = 0
, y = 2
,
Return 6
.
题解:
利用binary search来找四个边界。
举例找左边第一个'1', 从横向的0到y, 取mid, 若是mid对应的这一列若是包含'1', 说明左边第一个'1'在mid左侧,在mid左侧继续查找.
找右侧第一个'0', 从很像的y+1到image[0].length, 取mid, 若是mid对应的这一列包含'1', 说明右边第一个'0'在mid右侧,在mid右侧继续查找.
右侧第一个'0'的index 减掉 左侧第一个'1'的index 就是横向包含'1'的长度.
上下也是同理.
Time Complexity: O(m*logn + n*logm). Space: O(1).
AC Java:
1 public class Solution { 2 public int minArea(char[][] image, int x, int y) { 3 if(image == null || image.length == 0 || image[0].length == 0){ 4 return 0; 5 } 6 int m = image.length; 7 int n = image[0].length; 8 9 if(x<0 || x>=m || y<0 || y>=n){ 10 return 0; 11 } 12 13 int left = binarySearch(image, 0, y, 0, m, true, true); //左边第一个 '1' 14 int right = binarySearch(image, y+1, n, 0, m, true, false); //右边第一个 '0' 15 int up = binarySearch(image, 0, x, 0, n, false, true); // 上边第一个 '1' 16 int down = binarySearch(image, x+1, m, 0, n, false, false); //下边第一个 '0' 17 18 return (right-left) * (down - up); 19 } 20 21 private int binarySearch(char [][] image, int low, int high, int min, int max, boolean searchHor, boolean searchFirstOne){ 22 while(low < high){ 23 int mid = low + (high - low)/2; 24 25 boolean existBlack = false; 26 for(int i = min; i<max; i++){ 27 if((searchHor ? image[i][mid] : image[mid][i]) == '1'){ 28 existBlack = true; 29 break; 30 } 31 } 32 33 if(existBlack == searchFirstOne){ 34 high = mid; 35 }else{ 36 low = mid+1; 37 } 38 } 39 return low; 40 } 41 }