题目来源
题目描述
图片在计算机处理中往往是使用二维矩阵来表示的。
假设,这里我们用的是一张黑白的图片,那么 0 代表白色像素,1 代表黑色像素。
其中黑色的像素他们相互连接,也就是说,图片中只会有一片连在一块儿的黑色像素(像素点是水平或竖直方向连接的)。
那么,给出某一个黑色像素点 (x, y) 的位置,你是否可以找出包含全部黑色像素的最小矩形(与坐标轴对齐)的面积呢?
class Solution {
public:
/**
* @param image: a binary matrix with '0' and '1'
* @param x: the location of one of the black pixels
* @param y: the location of one of the black pixels
* @return: an integer
*/
int minArea(vector<vector<char>> &image, int x, int y) {
// write your code here
}
};
题目解析
二分查找
分析: 把二维图形投影到一维数组,并使用二分查找的方法来找边界。
思路: 二分找到四个方向上黑色像素点出现的坐标极大值
简单的线性查找
思路:遍历所有的像素点,记录黑色像素的最大和最小值
class Solution {
public:
int minArea(vector<vector<char>>& image, int x, int y) {
int left = y, right = y, up = x, down = x;
for (int i = 0; i < image.size(); ++i) {
for (int j = 0; j < image[i].size(); ++j) {
if (image[i][j] == '1') {
left = min(left, j);
right = max(right, j);
up = min(up, i);
down = max(down, i);
}
}
}
return (right - left + 1) * (down - up + 1);
}
};