4.11
数组统一赋值的函数Arrays.fill();
感觉自己的想法很野啊,用总的点的个数去减。
就是要注意边界值,数组是从下标0开始的,一定要注意。
public class Solution {
/**
* @param grid a boolean 2D matrix
* @return an integer
*/
public static int numIslands(boolean[][] grid) {
//flag数组用来存储是否访问过了
int N = grid.length;
if(N <= 0){
return 0;
}//行数
int M = grid[0].length;
if(M <=0){
return 0;}//列数
int count = M*N;
boolean[][] flag = new boolean[N][M];
for(int i = 0;i < N;i++){
for(int j = 0;j < M;j++){
if(flag[i][j] == false){
flag[i][j] =true;
if(grid[i][j] == false){
count --;
}
else{
count = around(i,j,grid,flag,M,N,count);
}
}
}
}
return count;// Write your code here
}
//给定一个点,判断它的四周
public static int around(int i,int j,boolean[][] grid,boolean[][] flag,int m,int n,int count) {
//上边
if(i-1 >=0 && flag[i-1][j] ==false){
flag[i-1][j] = true;
if(grid[i-1][j] == true){
count --;
count = around(i-1,j,grid,flag,m,n,count);
}
else{
count --;
}
}
//下边
if(i+1 < n && flag[i+1][j] ==false){
flag[i+1][j] = true;
if(grid[i+1][j] == true){
count --;
count = around(i+1,j,grid,flag,m,n,count);
}
else{
count --;
}
}
//左边
if(j-1 >=0 && flag[i][j-1] ==false){
flag[i][j-1] = true;
if(grid[i][j-1] == true){
count --;
count = around(i,j-1,grid,flag,m,n,count);
}
else{
count --;
}
}
//右边
if(j+1 < m && flag[i][j+1] ==false){
flag[i][j+1] = true;
if(grid[i][j+1] == true){
count --;
count = around(i,j+1,grid,flag,m,n,count);
}
else{
count --;
}
}
return count;
}
}
本文介绍了一种计算二维矩阵中岛屿数量的方法。通过遍历矩阵,使用递归深度优先搜索标记并计数每个岛屿,实现自动计算。文章提供了一个完整的Java实现示例。
3025

被折叠的 条评论
为什么被折叠?



