# floodfill问题——岛屿的最大面积

## 问题描述

[[0,0,1,0,0,0,0,1,0,0,0,0,0],
[0,0,0,0,0,0,0,1,1,1,0,0,0],
[0,1,1,0,1,0,0,0,0,0,0,0,0],
[0,1,0,0,1,1,0,0,1,0,1,0,0],
[0,1,0,0,1,1,0,0,1,1,1,0,0],
[0,0,0,0,0,0,0,0,0,0,1,0,0],
[0,0,0,0,0,0,0,1,1,1,0,0,0],
[0,0,0,0,0,0,0,1,1,0,0,0,0]]

[[0,0,0,0,0,0,0,0]]

## 代码

public class MaxAreaOfIsland {
int[][] g;
int max = 0;
int sum = 0;
public int maxAreaOfIsland(int[][] grid) {
if(null==grid||grid.length==0) return 0;
g = grid;
for(int i=0;i<grid.length;i++){
for(int j=0;j<grid[0].length;j++){
if(grid[i][j]==1){
dfs(i,j);
if(sum>max){
max = sum;
}
sum=0;
}
}
}
return max;
}

private void dfs(int i,int j){
sum++;
g[i][j] = 0;
for(int dx=-1;dx<=1;dx++){
for(int dy=-1;dy<=1;dy++){
//四联通限制
if(dx==0||dy==0){
int nx = i+dx;
int ny = j+dy;
if(nx>=0&&nx<g.length&&ny>=0&&ny<g[0].length&&g[nx][ny]==1){
dfs(nx,ny);
}
}
}
}
}

public static void main(String[] args) {
System.out.println(new MaxAreaOfIsland().maxAreaOfIsland(new int[][]{{1,1,0,1,1}, {1,0,0,0,0}, {0, 0,0,0,1}, {1,1,0,1,1}}));
}

}



## 扩展

public class NumOfWater {
int[][] g;
public int numOfWater(int[][] grid) {
if(null==grid||grid.length==0) return 0;
int num = 0;
g = grid;
for(int i=0;i<grid.length;i++){
for(int j=0;j<grid[0].length;j++){
if(grid[i][j]==1){
dfs(i,j);
num++;//湖泊的个数+1
}
}
}
return num;
}
private void dfs(int i,int j){
g[i][j] = 0;
for(int dx=-1;dx<=1;dx++){
for(int dy=-1;dy<=1;dy++){
//四联通限制
if(dx==0||dy==0){
int nx = i+dx;
int ny = j+dy;
if(nx>=0&&nx<g.length&&ny>=0&&ny<g[0].length&&g[nx][ny]==1){
dfs(nx,ny);
}
}
}
}
}

public static void main(String[] args) {
System.out.println(new NumOfWater().numOfWater(new int[][]{{1,1,0,1,1}, {1,0,0,0,0}, {0, 0,0,0,1}, {1,1,0,1,1}}));
}

}



©️2019 CSDN 皮肤主题: 书香水墨 设计师: CSDN官方博客