[Google] LeetCode 302 Smallest Rectangle Enclosing Black Pixels
You are given an m x n
binary matrix image
where 0
represents a white pixel and 1
represents a black pixel.
The black pixels are connected (i.e., there is only one black region). Pixels are connected horizontally and vertically.
Given two integers x
and y
that represents the location of one of the black pixels, return the area of the smallest (axis-aligned) rectangle that encloses all black pixels.
You must write an algorithm with less than \(O(mn)\) runtime complexity
Solution
用 \(DFS\) 来找到联通块,然后将这些位置 \(push\_back\) 到 \(vector\) 中。维护上下左右的边界。当然也可以不用我这么复杂的分类讨论
点击查看代码
class Solution {
private:
vector<vector<int>> loc;
int vis[102][102];
int dir[4][2]={
0,1,
1,0,
-1,0,
0,-1
};
bool check(int x,int y,int r,int c){
if(x<0||y<0||x>=r||y>=c)return false;
return true;
}
void dfs(int x,int y,int r,int c, vector<vector<char>>& img){
vis[x][y]=1;
loc.push_back({x,y});
for(int i=0;i<4;i++){
int nx=x+dir[i][0], ny=y+dir[i][1];
if(check(nx,ny,r,c) && !vis[nx][ny] && img[nx][ny]=='1')dfs(nx,ny,r,c,img);
}
}
public:
int minArea(vector<vector<char>>& image, int x, int y) {
int r = image.size(), c = image[0].size();
int stx, sty;
for(int i=0;i<r;i++){
for(int j=0;j<c;j++){
if(image[i][j]=='1'){stx=i;sty=j;break;}
}
}
dfs(stx,sty,r,c,image);
int tp=INT_MAX, bk = INT_MIN, lf=INT_MAX, rg=INT_MIN;
for(auto ele:loc){
tp=min(tp,ele[0]); bk = max(bk, ele[0]);
lf=min(lf,ele[1]); rg = max(rg, ele[1]);
}
if(x>=tp && x<=bk && y>=lf && y<=rg)return (bk-tp+1)*(rg-lf+1);
if(y<lf){
if(x<tp)return (bk-x+1)*(rg-y+1);
else if(x>=tp && x<=bk)return (bk-tp+1)*(rg-y+1);
else return (rg-y+1)*(x-tp+1);
}
else if(y>=lf && y<=rg){
if(x<tp) return (rg-lf+1)*(bk-x+1);
else if(x>tp) return (rg-lf+1)*(x-tp+1);
}
else if(y>rg){
if(x<tp) return (y-lf+1)*(bk-x+1);
else if(x>=tp && x<=bk)return (y-lf+1)*(bk-tp+1);
else return (y-lf+1)*(x-tp+1);
}
return 0;
}
};