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;
}
};
本文介绍了一种算法,用于寻找包含特定黑色像素点的最小矩形区域。通过二分搜索法确定矩形的顶部、底部、左侧和右侧边界,从而高效地计算出矩形的面积。
2340

被折叠的 条评论
为什么被折叠?



