Smallest Rectangle Enclosing Black Pixels
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.
Solution
public class Solution {
public int minArea(char[][] image, int x, int y) {
if (image == null || image.length == 0) return 0;
int row = image.length;
int column = image[0].length;
if (!validate(x, y, row, column)) return 0;
List<Point> pointList = new ArrayList<>();
boolean[][] visit = new boolean[row][column];
traverse(image, visit, x, y, row, column, pointList);
if (pointList.isEmpty()) return 0;
Point point = pointList.get(0);
int minX = point.x;
int maxX = point.x;
int minY = point.y;
int maxY = point.y;
for (int i = 1; i < pointList.size(); i++) {
point = pointList.get(i);
minX = Math.min(minX, point.x);
maxX = Math.max(maxX, point.x);
minY = Math.min(minY, point.y);
maxY = Math.max(maxY, point.y);
}
return (Math.abs(minX - maxX) + 1) * (Math.abs(minY - maxY) + 1);
}
private void traverse(char[][] image, boolean[][] visit, int x, int y, int row, int column, List<Point> points) {
if (!validate(x, y, row, column) || visit[x][y]) return;
visit[x][y] = true;
if (image[x][y] == '1') {
points.add(new Point(x, y));
traverse(image, visit, x + 1, y, row, column, points);
traverse(image, visit, x - 1, y, row, column, points);
traverse(image, visit, x, y + 1, row, column, points);
traverse(image, visit, x, y - 1, row, column, points);
}
}
private class Point {
int x;
int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
private boolean validate(int x, int y, int row, int column) {
return x >= 0 && x < row && y >= 0 && y < column;
}
}