[LeetCode302]Smallest Rectangle Enclosing Black Pixels

Hard ..

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.

Hide Company Tags Google
Hide Tags Binary Search

如果選中的點是白色,那麼最小的面積就是選中的點作爲一個邊界,加上整個黑色面積。若選中的是黑色,那麼最小面積就是整個黑色面積(因爲它們連在一起)。

class Solution {
public:
    int minArea(vector<vector<char>>& image, int x, int y) {
        int m = image.size(), n = image[0].size();
        int top = searchRow(image, 0, x, 0, n, true);
        int bottom = searchRow(image, x+1, m, 0, n, false);
        int left = searchCols(image, 0, y, top, bottom, true);
        int right = searchCols(image, y+1, n, top, bottom, false);
        return (bottom - top) * (right - left);
    }
    int searchRow(vector<vector<char>>& image, int start, int end, int lo, int hi, bool opt){
        while(start != end){
            int k = lo, mid = start + (end-start)/2;
            while(k < hi && image[mid][k] == '0') ++k;
            if(k<hi == opt) end = mid;// k<hi && opt || k>hi && !opt
            else start = mid + 1;
        }
        return start;
    }
    int searchCols(vector<vector<char>>& image, int start, int end, int lo, int hi, bool opt){
        while(start != end){
            int k = lo, mid = start + (end - start)/2;
            while(k < hi && image[k][mid] == '0') ++k;
            if(k < hi == opt) end = mid;
            else start = mid + 1;
        }
        return start;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章