302 Smallest Rectangle Enclosing Black Pixels

1. Question

An image is represented by a binary matrix with0as a white pixel and1as 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:
1
[
2
"0010",
3
"0110",
4
"0100"
5
]
Copied!
andx = 0,y = 2,
Return6.

2. Implementation

(1) Binary Search
1
class Solution {
2
public int minArea(char[][] image, int x, int y) {
3
int m = image.length, n = image[0].length;
4
5
int left = lowerBound(image, 0, y, false);
6
int right = upperBound(image, y, n - 1, false);
7
int top = lowerBound(image, 0, x, true);
8
int bottom = upperBound(image, x, m - 1, true);
9
10
return (right - left + 1) * (bottom - top + 1);
11
}
12
13
public int lowerBound(char[][] image, int start, int end, boolean searchInRow) {
14
int mid = 0;
15
16
while (start + 1 < end) {
17
mid = start + (end - start) / 2;
18
if (!isBlackPixel(image, mid, searchInRow)) {
19
start = mid + 1;
20
}
21
else {
22
end = mid;
23
}
24
}
25
26
if (isBlackPixel(image, start, searchInRow)) {
27
return start;
28
}
29
else {
30
return end;
31
}
32
}
33
34
public int upperBound(char[][] image, int start, int end, boolean searchInRow) {
35
int mid = 0;
36
37
while (start + 1 < end) {
38
mid = start + (end - start) / 2;
39
if (!isBlackPixel(image, mid, searchInRow)) {
40
end = mid - 1;
41
}
42
else {
43
start = mid;
44
}
45
}
46
47
if (isBlackPixel(image, end, searchInRow)) {
48
return end;
49
}
50
else {
51
return start;
52
}
53
}
54
55
public boolean isBlackPixel(char[][] image, int index, boolean searchInRow) {
56
if (searchInRow) {
57
for (int col = 0; col < image[0].length; col++) {
58
if (image[index][col] == '1') {
59
return true;
60
}
61
}
62
}
63
else {
64
for (int row = 0; row < image.length; row++) {
65
if (image[row][index] == '1') {
66
return true;
67
}
68
}
69
}
70
return false;
71
}
72
}
Copied!

3. Time & Space Complexity

Binary Search: 时间复杂度: O(mlogn + nlogm), 空间复杂度O(1)