302. Smallest Rectangle Enclosing Black Piels

题目:
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.

解答:
这道题我第一眼看到就想到dfs把每个点都扫一遍,找到最小最大边界值,然后作差相乘。但是我知道这是有冗余的,只需要边界值的话,并不需要扫每一个点,查找的话,最快还是binary search,所以有个第二种解法,但是边界还是很容易出错,要分清取舍。
1.DFS

private class Interval{
int min, max;
public Interval(int min, int max) {
this.min = min;
this.max = max;
}
}

public void search(char[][] image, int x, int y, Interval row, Interval col, boolean[][] visited) {
visited[x][y] = true;
row.max = Math.max(row.max, x);
row.min = Math.min(row.min, x);
col.max = Math.max(col.max, y);
col.min = Math.min(col.min, y);
int[][] dir = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
for (int k = 0; k image.length - 1 || j image[0].length - 1) {
continue;
}
if (!visited[i][j] && image[i][j] == '1') {
search(image, i, j, row, col, visited);
}
}
}

public int minArea(char[][] image, int x, int y) {
if (image == null || image.length == 0 || image[0].length == 0) return 0;

int m = image.length, n = image[0].length;Interval row = new Interval(m - 1, 0);Interval col = new Interval(n - 1, 0);boolean[][] visited = new boolean[m][n];search(image, x, y, row, col, visited);return (row.max - row.min + 1) * (col.max - col.min + 1);

}
2.Binary Search

public int searchColumns(char[][] image, int i, int j, int top, int bottom, String def) {
while (i != j) {
int k = top, mid = (i + j) / 2;
while (k = bottom && def.equals("max")) {
j = mid;
} else {
i = mid + 1;
}
}
return i;
}

public int searchRows(char[][] image, int i, int j, int left, int right, String def) {
while (i != j) {
int k = left, mid = (i + j) / 2;
while (k = right && def.equals("max")) {
j = mid;
} else {
i = mid + 1;
}
}
return i;
}

public int minArea(char[][] image, int x, int y) {
if (image == null || image.length == 0 || image[0].length == 0) return 0;
int m = image.length, n = image[0].length;
int left = searchColumns(image, 0, y, 0, m, "min");
int right = searchColumns(image, y + 1, n, 0, m, "max");
int top = searchRows(image, 0, x, left, right, "min");
int bottom = searchRows(image, x + 1, m, left, right, "max");

return (right - left) * (bottom - top);

}

关键字:leetcode, java, dfs


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部