1、题目:
链接:https://leetcode.com/problems/smallest-rectangle-enclosing-black-pixels/(注:该链接你不一定能打开)
内容: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.
样例:
given the following image:
[
"0010",
"0110",
"0100"
]
and x = 0, y = 2,Return 6.
2、分析
这里,我们就以给定的例子进行分析。要找到最小的矩形区域,我们需要找到这个矩形区域的最左侧left,最右侧right,最上侧top,最下侧down。我们从给定的点(0,2)开始,利用BFS算法进行计算。每次检测它上下左右四个点(如果有),然后根据这四个点来更新left,right,top和down的值。
3、代码
BFS:
class Solution {
public:
int minArea(vector<vector<char>>& image, int x, int y) {
if (image.empty()) {
return 0;
}
int left = y, right = y, top = x, down = x;
queue<pair<int, int>> que;
pair<int, int> p = make_pair(x, y), q;
que.push(p);
image[p.first][p.second] = '0'; // 该点为1,且访问过就将该点置为0;
while (!que.empty()) {
p = que.front();
que.pop();
// 检测p点左侧的点
if (p.second != 0 && image[p.first][p.second - 1] == '1') {
image[p.first][p.second - 1] = '0';
q = make_pair(p.first, p.second - 1);
que.push(q);
left = left < (p.second - 1) ? left : (p.second - 1);
}
// 检测p点右侧的点
if (p.second != image[0].size() - 1 && image[p.first][p.second + 1] == '1') {
image[p.first][p.second + 1] = '0';
q = make_pair(p.first, p.second + 1);
que.push(q);
right = right > (p.second + 1) ? right : (p.second + 1);
}
// 检测p点上面的点
if (p.first != 0 && image[p.first - 1][p.second] == '1') {
image[p.first - 1][p.second] = '0';
q = make_pair(p.first - 1, p.second);
que.push(q);
top = top < (p.first - 1) ? top : (p.first - 1);
}
// 检测p点下面的点
if (p.first != image.size() - 1 && image[p.first + 1][p.second] == '1') {
image[p.first + 1][p.second] = '0';
q = make_pair(p.first + 1, p.second);
que.push(q);
down = down > (p.first + 1) ? down : (p.first + 1);
}
}
return (right - left + 1) * (down - top + 1);
}
};
DFS:
class Solution {
public:
int minArea(vector<vector<char>>& image, int x, int y) {
int left = y, right = y, top = x, down = x;
dfs(image, x, y, left, right, top, down);
return (right - left + 1) * (down - top + 1);
}
void dfs(vector<vector<char>>& image, int x, int y, int &left, int &right, int &top, int &down) {
if (x < 0 || x >= image.size() || y < 0 || y >= image[0].size() || image[x][y] != '1') {
return ;
}
image[x][y] = '0';
left = min(y, left);
right = max(y, right);
top = min(x, top);
down = max(x, down);
dfs(image, x - 1, y, left, right, top, down);
dfs(image, x + 1, y, left, right, top, down);
dfs(image, x, y - 1, left, right, top, down);
dfs(image, x, y + 1, left, right, top, down);
}
};