An image is represented by a binary matrix with0
as a white pixel and1
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.
Example:
Input:
[
"0010",
"0110",
"0100"
]
and
x = 0
,
y = 2
Output:
6
class Solution {
public int minArea(char[][] image, int x, int y) {
int n = image.length, m = image[0].length;
boolean[][] visited = new boolean[n][m];
int minX = x, maxX = x, minY = y, maxY = y;
Queue<int[]> q = new LinkedList<>();
q.add(new int[]{x, y});
visited[x][y] = true;
int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
while (!q.isEmpty()){
int[] cur = q.poll();
for (int i = 0; i < 4; i++){
int xx = cur[0] + dirs[i][0];
int yy = cur[1] + dirs[i][1];
if (xx < 0 || xx >= n || yy < 0 || yy >= m || visited[xx][yy] || image[xx][yy] == '0') continue;
minX = Math.min(minX, xx);
maxX = Math.max(maxX, xx);
minY = Math.min(minY, yy);
maxY = Math.max(maxY, yy);
visited[xx][yy] = true;
q.add(new int[]{xx, yy});
}
}
return (maxY - minY + 1) * (maxX - minX + 1);
}
}