题目解析:找到最大连通块。并查集模板题。
class Solution {
public:
int maxAreaOfIsland(vector<vector<int>>& grid)
{
if(grid.empty()) return 0 ;
int m = grid.size() , n = grid[0].size() ;
root = vector<int>(m * n , 0) ;
cnt = vector<int>(m * n , 0) ;
int cnt1 = 0 ;
for(int i = 0 ; i < m ; i++)
for(int j = 0 ; j < n ; j++)
{
root[i * n + j] = i * n + j ;
if(grid[i][j] == 1)
{
cnt[i * n + j] = 1 ;
cnt1++ ;
}
}
if(cnt1 == 0) return 0 ;
int res = INT_MIN ;
for(int i = 0 ; i < m ; i++)
for(int j = 0 ; j < n ; j++)
{
if(grid[i][j] == 0) continue ;
res = max(res , cnt[find(i*n+j)]) ;
for(int k = 0 ; k < 4 ; k++)
{
int ni = i + dir[k] , nj = j + dir[k + 1] ;
if(ni < 0 || ni >= m || nj < 0 || nj >= n || grid[ni][nj] == 0) continue ;
int x = find(i * n + j) , y = find(ni * n + nj) ;
if(x != y)
{
root[x] = y ;
cnt[y] += cnt[x] ;
res = max(res , cnt[y]) ;
}
}
}
return res ;
}
private:
vector<int> root , cnt , dir = {-1 , 0 , 1 , 0 , -1};
int find(int x)
{
return root[x] == x ? x : root[x] = find(root[x]) ;
}
};
dfs解法:其实也是查找连通块的另一种解法
class Solution {
public:
int maxAreaOfIsland(vector<vector<int>>& grid)
{
if(grid.empty()) return 0 ;
m = grid.size() ;
n = grid[0].size() ;
vis = vector<int>(m * n , 0) ;
int res = 0 ;
for(int i = 0 ; i < m ; i++)
for(int j = 0 ; j < n ; j++)
{
if(grid[i][j] == 0 || vis[i * n + j]) continue ;
int cnt = 0 ;
dfs(i , j , cnt, grid) ;
res = max(res , cnt) ;
}
return res ;
}
private:
vector<int> vis , dir = {-1 , 0 , 1 , 0 , -1};
int m , n ;
void dfs(int i , int j , int& cnt , vector<vector<int>>& grid)
{
cnt++ ;
vis[i * n + j] = 1 ;
for(int k = 0 ; k < 4 ; k++)
{
int ni = i + dir[k] , nj = j + dir[k + 1] ;
if(ni < 0 || ni >= m || nj < 0 || nj >= n || grid[ni][nj] == 0 || vis[ni * n + nj]) continue ;
dfs(ni , nj , cnt , grid) ;
}
}
};
dfs里为了避免陷入循环,在dfs之前应该要将vis值置1
leetcode 695. Max Area of Island
原文:https://www.cnblogs.com/mychen06/p/12636486.html