/** 面试题 16.19. 水域大小
* @author 作者 Your-Name:
* @version 创建时间:2020年3月3日 上午10:27:57
* 你有一个用于表示一片土地的整数矩阵land,该矩阵中每个点的值代表对应地点的海拔高度。若值为0则表示水域。由垂直、水平或对角连接的水域为池塘。池塘的大小是指相连接的水域的个数。编写一个方法来计算矩阵中所有池塘的大小,返回值需要从小到大排序。
示例:
输入:
[
[0,2,1,0],
[0,1,0,1],
[1,1,0,1],
[0,1,0,1]
]
输出: [1,2,4]
提示:
0 < len(land) <= 1000
0 < len(land[i]) <= 1000
*/
public class 水域大小 {
int x=0;
int y=0;
List<Integer> list = new ArrayList<>();
public int[] pondSizes(int[][] land)
{
if(land.length==0&&land[0].length==0)
return null;
for(int i=0;i<land.length;i++)
{
for(int j=0;j<land[0].length;j++)
{
if(land[i][j]==0)
{
list.add(dfs(land,i,j));
}
}
}
int[] array = new int[list.size()];
int m=0;
for(int n:list) {
array[m++] = n;
System.out.print(n+" ");
}
Arrays.sort(array);
return array;
}
public int dfs(int[][] land,int x,int y)
{
if(x<0||x>=land.length||y<0||y>=land[0].length||land[x][y]!=0)//控制不走出边界
{
return 0;
}
int temp=1;
land[x][y]=2;
temp+=dfs(land,x+1,y);
temp+=dfs(land,x,y+1);
temp+=dfs(land,x+1,y+1);
temp+=dfs(land,x+1,y-1);
temp+=dfs(land,x-1,y+1);
temp+=dfs(land,x-1,y-1);
temp+=dfs(land,x-1,y);
temp+=dfs(land,x,y-1);
return temp;
}
}