LintCode Q 600 - 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.
Example 1:Input:["0010","0110","0100"],x=0,y=2 ; Output:6
Explanation:
The upper left coordinate of the matrix is (0,1), and the lower right coordinate is (2,2).
Example 2:Input:["0000","0101","0000"],x=1,y=1 ; Output:3
Explanation:
The upper left coordinate of the matrix is (1,1), and the lower right coordinate is (1,3).
Solution
Solution : BFS
Code:
private static final int[] DIRS = new int[]{1, 0, -1, 0, 1};
public int minArea(char[][] image, int x, int y) {
int R = image.length, C = image[0].length;
Queue<int[]> que = new LinkedList<>();
que.offer(new int[]{x, y}); image[x][y] = '0';
int l = x, r = x, t = y, b = y;
while (!que.isEmpty()) {
int[] curr = que.poll();
for (int i = 0; i < 4; i++) {
int nr = curr[0] + DIRS[i];
int nc = curr[1] + DIRS[i + 1];
if (nr < 0 || nc < 0 || nr == R || nc == C || image[nr][nc] != '1') continue;
que.offer(new int[]{nr, nc});
image[nr][nc] = '0';
l = Math.min(l, nr); r = Math.max(r, nr);
t = Math.min(t, nc); b = Math.max(b, nc);
}
}
return (r - l + 1) * (b - t + 1);
}