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.
Example
For example, given the following image:
[
"0010",
"0110",
"0100"
]
and x = 0
, y = 2
,
Return 6
.
java
public class Solution {
/*
* @param image: a binary matrix with '0' and '1'
* @param x: the location of one of the black pixels
* @param y: the location of one of the black pixels
* @return: an integer
*/
public int minArea(char[][] image, int x, int y) {
// write your code here
if (image == null || image.length == 0 ||
image[0] == null || image[0].length == 0) {
return 0;
}
int left = findLeft(image, 0, y);
int right = findRight(image, y, image[0].length - 1);
int top = findTop(image, x, image.length - 1);
int bottom = findBottom(image, 0, x);
return (right - left + 1) * (top - bottom + 1);
}
private int findLeft(char[][] image, int start, int end) {
int mid = 0;
while (start + 1 < end) {
mid = (end - start) / 2 + start;
if (isPixel1(image, mid)) {
end = mid;
} else {
start = mid;
}
}
if (isPixel1(image, start)) {
return start;
}
return end;
}
private int findRight(char[][] image, int start, int end) {
int mid = 0;
while (start + 1 < end) {
mid = (end - start) / 2 + start;
if (isPixel1(image, mid)) {
start = mid;
} else {
end = mid;
}
}
if (isPixel1(image, end)) {
return end;
}
return start;
}
private int findTop(char[][] image, int start, int end) {
int mid = 0;
while (start + 1 < end) {
mid = (end - start) / 2 + start;
if (isPixel2(image, mid)) {
start = mid;
} else {
end = mid;
}
}
if (isPixel2(image, end)) {
return end;
}
return start;
}
private int findBottom(char[][] image, int start, int end) {
int mid = 0;
while (start + 1 < end) {
mid = (end - start) / 2 + start;
if (isPixel2(image, mid)) {
end = mid;
} else {
start = mid;
}
}
if (isPixel2(image, start)) {
return start;
}
return end;
}
private boolean isPixel1(char[][] image, int column) {
for (int i = 0; i < image.length; i++) {
if (image[i][column] == '1') {
return true;
}
}
return false;
}
private boolean isPixel2(char[][] image, int row) {
for (int i = 0; i < image[0].length; i++) {
if (image[row][i] == '1') {
return true;
}
}
return false;
}
}