您的位置:首页 > 产品设计 > UI/UE

302. Smallest Rectangle Enclosing Black Pixels My Submissions QuestionEditorial Solution

2016-03-31 12:13 651 查看
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
.

public class Solution {
public int minArea(char[][] image, int x, int y) {
int m = image.length;
int n = image[0].length;

int left = bsHor(image, 0, y, 0, m, true);
int right = bsHor(image, y+1, n, 0, m, false);
int top = bsVer(image, 0, x, left, right, true);
int bottom = bsVer(image, x+1, m, left, right, false);

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

private int bsHor(char[][] image, int i, int j, int top, int bottom, boolean leftSide) {
while (i != j) {
int k = top;
int mid = (j - i) / 2 + i;
while (k<bottom && image[k][mid] == '0') k++;
if (k < bottom == leftSide) {
j = mid;
} else {
i = mid + 1;
}
}
return i;
}

private int bsVer(char[][] image, int i, int j, int left, int right, boolean upSide) {
while (i != j) {
int k = left;
int mid = (j - i) / 2 + i;
while (k<right && image[mid][k] == '0') k++;
if (k < right == upSide) {
j = mid;
} else {
i = mid + 1;
}
}
return i;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: