433-岛屿的个数

本文介绍了一种计算二维矩阵中岛屿数量的方法。通过遍历矩阵,使用递归深度优先搜索标记并计数每个岛屿,实现自动计算。文章提供了一个完整的Java实现示例。

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;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值