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.
Imagine we project the 2D array to the bottom axis with the rule "if a column has any black pixel it‘s projection is black otherwise white". The projected 1D array is "0110"
Theorem
If there are only one black pixel region, then in a projected 1D array all the black pixels are connected.
This means we can do 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, do the binary search in the [0, y)
range and find the first column vector who has any black pixel.
To determine if a column vector has a black pixel is O(m)
so the search in total is O(m log n)
We can do the same for the other boundaries. The area is then calculated by the boundaries. Thus the algorithm runs in O(m log n + n log m)
1 public class Solution { 2 public int minArea(char[][] image, int x, int y) { 3 int m = image.length; 4 int n = image[0].length; 5 int left = searchLeft(image, y); 6 int right = searchRight(image, y); 7 int top = searchTop(image, x); 8 int bottom = searchBottom(image, x); 9 return (right-left+1)*(bottom-top+1); 10 } 11 12 public int searchLeft(char[][] image, int right) { 13 int l = 0, r = right; 14 while (l <= r) { 15 int m = (l+r)/2; 16 if (!findBlack(image, m, false)) l = m+1; 17 else r = m-1; 18 } 19 return l; 20 } 21 22 public int searchRight(char[][] image, int left) { 23 int l = left, r = image[0].length-1; 24 while (l <= r) { 25 int m = (l+r)/2; 26 if (!findBlack(image, m, false)) r = m-1; 27 else l = m+1; 28 } 29 return r; 30 } 31 32 public int searchTop(char[][] image, int bottom) { 33 int l = 0, r = bottom; 34 while (l <= r) { 35 int m = (l+r)/2; 36 if (!findBlack(image, m, true)) l = m+1; 37 else r = m-1; 38 } 39 return l; 40 } 41 42 public int searchBottom(char[][] image, int top) { 43 int l=top, r=image.length-1; 44 while (l <= r) { 45 int m = (l+r)/2; 46 if (!findBlack(image, m, true)) r = m-1; 47 else l = m+1; 48 } 49 return r; 50 } 51 52 public boolean findBlack(char[][] image, int cur, boolean row) { 53 int m = image.length; 54 int n = image[0].length; 55 if (row) { 56 for (int i=0; i<n; i++) { 57 if (image[cur][i] == ‘1‘) 58 return true; 59 } 60 return false; 61 } 62 else { 63 for (int j=0; j<m; j++) { 64 if (image[j][cur] == ‘1‘) 65 return true; 66 } 67 return false; 68 } 69 } 70 }