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:

1
2
3
4
5
[
"0010",
"0110",
"0100"
]

and x = 0, y = 2,
Return 6.


求能覆盖与(x, y)的相邻的所有1的长方形的面积,其实就是就找所有与(x, y)相邻的点,求出x的最大值,最小值,y的最大值,最小值。

面积为(max - minx + 1) * (maxy - miny + 1).

方法1:遍历 包含BFS, DFS

很真观,就是遍历所有相邻的点。我自己写了个DFS的版本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
int minx = Integer.MAX_VALUE;
int miny = Integer.MAX_VALUE;
int maxx = Integer.MIN_VALUE;
int maxy = Integer.MIN_VALUE;
int[] dx = {0, 0, 1, -1};
int[] dy = {1, -1, 0, 0};
boolean[][] visited;
int m, n;
public int minArea(char[][] image, int x, int y) {
m = image.length;
n = image[0].length;
visited = new boolean[m][n];
dfs(image, x, y);
return (maxx - minx + 1) * (maxy - miny + 1);
}
public void dfs(char[][] image, int x, int y) {
if (x < 0 || x >= m || y < 0 || y >= n || visited[x][y])
return;
if (image[x][y] == '1') {
visited[x][y] = true;
minx = Math.min(x, minx);
maxx = Math.max(x, maxx);
miny = Math.min(y, miny);
maxy = Math.max(y, maxy);
for (int i = 0; i < 4; i++) {
dfs(image, x + dx[i], y + dy[i]);
}
}
}

Ref:

  1. https://discuss.leetcode.com/topic/29006/c-java-python-binary-search-solution-with-explanation
  2. https://discuss.leetcode.com/topic/30621/1ms-java-binary-search-dfs-is-4ms

我自己是想不到的,就看看别人的做法吧。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public int minArea(char[][] image, int x, int y) {
int m = image.length, n = image[0].length;
int colMin = binarySearch(image, true, 0, y, 0, m, true);
int colMax = binarySearch(image, true, y + 1, n, 0, m, false);
int rowMin = binarySearch(image, false, 0, x, colMin, colMax, true);
int rowMax = binarySearch(image, false, x + 1, m, colMin, colMax, false);
return (rowMax - rowMin) * (colMax - colMin);
}
public int binarySearch(char[][] image, boolean horizontal, int lower, int upper, int min, int max, boolean goLower) {
while (lower < upper) {
int mid = lower + (upper - lower) / 2;
boolean inside = false;
for (int i = min; i < max; i++) {
if ((horizontal ? image[i][mid] : image[mid][i]) == '1') {
inside = true;
break;
}
}
if (inside == goLower) {
upper = mid;
} else {
lower = mid + 1;
}
}
return lower;
}