这题有两种方式,
一种是DFS,一种是Binary search。
这里提供一个binary search简化后的代码。
public int minArea(char[][] image, int x, int y) {
int N = image.length, M = image[0].length;
int rx = x, cy = y;
int left = findLeftRight(image, 0, cy, true, true);
int right = findLeftRight(image, cy, M - 1, false, true);
int top = findLeftRight(image, 0, rx, true, false);
int bot = findLeftRight(image, rx, N - 1, false, false);
return (bot - top + 1) * (right - left + 1);
}
private boolean containsOne(char[][] image, int rc, boolean sweepRow) {
if (sweepRow) {
for (int row = 0; row < image.length; row++) {
if (image[row][rc] == '1') return true;
}
} else {
for (int col = 0; col < image[0].length; col++) {
if (image[rc][col] == '1') return true;
}
}
return false;
}
private int findLeftRight(char[][] im, int start, int end, boolean left, boolean sweepRow) {
while (start < end) {
int mid = left ? start + (end - start) / 2 : end - (end - start) / 2;
if (containsOne(im, mid, sweepRow)) {
//下面这一句是我原创的奇技淫巧,一行写完
int dummy = left ? (end = mid) : (start = mid);
} else {
int dummy = left ? (start = mid + 1) : (end = mid - 1);
}
}
return start;
}