695. 岛屿的最大面积
题目:
链接https://leetcode.cn/problems/max-area-of-island/
代码:
class Solution {
public:
pair<int,int> f[51][51];
int s[51][51];
int n,m;
int xy[4][2]={{-1,0},{1,0},{0,-1},{0,1}};
pair<int,int> getf(int x,int y){
if(f[x][y].first==x&&f[x][y].second==y)return f[x][y];
return f[x][y]=getf(f[x][y].first,f[x][y].second);
}
void mer(int x , int y,int x2 ,int y2){
pair<int,int> fx = getf(x,y),fy = getf(x2,y2);
if(fx==fy)return;
f[fx.first][fx.second] = fy;
s[fy.first][fy.second] += s[fx.first][fx.second];
}
int maxAreaOfIsland(vector<vector<int>>& grid) {
n = grid.size();
m= grid[0].size();
for(int i = 1 ; i <=n ; i++)
for(int j = 1; j <=m;j++)
if(grid[i-1][j-1]==1){
f[i][j]={i,j};
s[i][j] = 1;
}
for(int i = 1 ; i <=n ; i++){
for(int j = 1; j <=m;j++){
if(grid[i-1][j-1]==1)
for(int k=0;k<=3;k++){
int xj = i+xy[k][0],yj =j+xy[k][1];
if(xj<=0||xj>n||yj<=0||yj>m)continue;
if(grid[xj-1][yj-1]==1)mer(i,j,xj,yj);
}
}
}
int ans =0;
for(int i = 1 ; i <= n ; i++){
for(int j = 1 ; j <= m ; j++){
if(grid[i-1][j-1] == 1)
ans = max(ans ,s[i][j]);
}
}
return ans;
}
};