LeetCode刷题实战302:包含全部黑色像素的最小矩阵
An image is represented by a binary matrix with
0
as a white pixel and1
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.
示例
示例:
输入:
[
"0010",
"0110",
"0100"
]
和 x = 0, y = 2
输出: 6
解题
class Solution {
int x1 = INT_MAX, x2 = -1;
int y1 = INT_MAX, y2 = -1;
public:
int minArea(vector<vector<char>>& image, int x, int y) {
int m = image.size(), n = image[0].size(), i, j, nx, ny, k;
vector<vector<int>> dir = {{1,0},{0,1},{0,-1},{-1,0}};
queue<vector<int>> q;
q.push({x,y});
image[x][y] = '0';//访问过了
while(!q.empty())
{
i = q.front()[0];
j = q.front()[1];
q.pop();
x1 = min(x1, i);
x2 = max(x2, i);
y1 = min(y1, j);
y2 = max(y2, j);
for(k = 0; k < 4; ++k)
{
nx = i + dir[k][0];
ny = j + dir[k][1];
if(nx>=0 && nx<m && ny>=0 && ny<n && image[nx][ny]=='1')
{
q.push({nx, ny});
image[nx][ny] = '0';//访问过了
}
}
}
return (x2-x1+1)*(y2-y1+1);
}
};