An image is represented by a binary matrix with0as a white pixel and1as 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.

Have you met this question in a real interview?

Yes

Example

For example, given the following image:

[
  "0010",
  "0110",
  "0100"
]

and x =0, y =2,
Return6.

class Solution {

public:

/\*\*

 \* @param image a binary matrix with '0' and '1'

 \* @param x, y the location of one of the black pixels

 \* @return an integer

 \*/

int minArea\(vector<vector<char>>& image, int x, int y\) {

    int m = image.size\(\), n = image\[0\].size\(\);

    int top = searchRows\(image, 0, x, 0, n, true\);

    int bottom = searchRows\(image, x + 1, m, 0, n, false\);

    int left = searchColumns\(image, 0, y, top, bottom, true\);

    int right = searchColumns\(image, y + 1, n, top, bottom, false\);

    return \(right - left\) \* \(bottom - top\);

}



int searchRows\(vector<vector<char>>& image, int i, int j, int low, int high, bool opt\) {

    while \(i != j\) {

        int k = low, mid = \(i + j\) / 2;

        while \(k < high && image\[mid\]\[k\] == '0'\) ++k;

        if \(k < high == opt\)

            j = mid;

        else

            i = mid + 1;

    }

    return i;

}

int searchColumns\(vector<vector<char>>& image, int i, int j, int low, int high, bool opt\) {

    while \(i != j\) {

        int k = low, mid = \(i + j\) / 2;

        while \(k < high && image\[k\]\[mid\] == '0'\) ++k;

        if \(k < high == opt\)

            j = mid;

        else

            i = mid + 1;

    }

    return i;

}

};

results matching ""

    No results matching ""