查找最大的连通面积
695. Max Area of Island (Medium)
[[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]]
题目描述:
矩阵中1表示小岛,0表示海水,题目要求求出最大的联通面积。
思路分析:
使用深度优先搜索,在遍历到1时,从1出发,继续向四周遍历,直到周围没有1,计算出联通面积,访问过的点不能再访问。
代码:
class Solution {
public int maxAreaOfIsland(int [][]grid){
if(grid==null||grid.length==0)
return 0;
int m=grid.length;
int n=grid[0].length;
int maxArea=0;
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
maxArea=Math.max(maxArea,dfs(grid,i,j));
}
}
return maxArea;
}
public int dfs(int [][]grid,int r,int c){
int [][]direction={{0,1},{0,-1},{1,0},{-1,0}};
if(r<0||r>=grid.length||c<0||c>=grid[0].length||grid[r][c]==0)
return 0;
grid[r][c]=0; //标记已经访问过
int area=1;
for(int[] d:direction){
area+=dfs(grid,r+d[0],c+d[1]);
}
return area;
}
}