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) {
        // binary search in four direction
        int up, down, left, right;

        up = binary(image, 0, x-1, true, false);
        down = binary(image, x+1, image.length-1, true, true);

        left = binary(image, 0, y-1, false, false);
        right = binary(image, y+1, image[0].length-1, false, true);

        return (down - up + 1) * (right - left + 1);
    }

    public int binary(char[][] image, int left, int right, boolean row, boolean leftTarget) {
        while(left <= right) {
            int mid = (left + right) / 2;
            if(black(image, mid, row) == leftTarget) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }

        return leftTarget ? left-1 : left;
    }

    public boolean black(char[][] image, int j, boolean row) {
        if(row) {
            for(int i = 0; i < image[0].length; i++) {
                if(image[j][i] == '1') return true;
            }
        } else {
            for(int i = 0; i < image.length; i++) {
                if(image[i][j] == '1') return true;
            }
        }
        return false;
    }
}

results matching ""

    No results matching ""