topic
Given a two-dimensional array of non-null grid number 0 and 1, is an island formed of a combination of four directions (horizontal or vertical) 1 (representing the land). You can assume that the four edges of the two-dimensional matrix are surrounded by water.
Find a given two-dimensional array in the largest island in the area. (If there are no islands, the area is returned to 0.)
answer
dis / bfs bare bare bare title.
Their search practice too little, he wanted more practice!
all
bfs version
Code (dfs)
class Solution {
public int maxAreaOfIsland(int[][] grid) {
int maxArea=0;
if(grid==null){
return 0;
}
for(int i=0;i<grid.length;++i){
for(int j=0;j<grid[0].length;++j){
if(grid[i][j]==1){
int area=dfs(grid,i,j);
maxArea=area>maxArea?area:maxArea;
}
}
}
return maxArea;
}
public int dfs(int[][] grid,int i,int j){
int area=1;
grid[i][j]=0;
int[] dx={0,0,-1,1};
int[] dy={-1,1,0,0};
for(int m=0;m<4;++m){
if(vaild(grid,i+dx[m],j+dy[m])&&grid[i+dx[m]][j+dy[m]]==1){
area+=dfs(grid,i+dx[m],j+dy[m]);
}
}
return area;
}
public boolean vaild(int[][] grid,int i,int j){
return i>=0&&i<grid.length&&j>=0&&j<grid[0].length;
}
}