leetcode:Number of Islands

原题为:

Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.

Example 1:

11110
11010
11000
00000

Answer: 1

Example 2:

11000
11000
00100
00011

Answer: 3

原题地址:https://leetcode.com/problems/number-of-islands/

思路:

应该是深度递归遍历,思路很简单,就是碰到一个值是‘1’的位置,就从这个位置开始扩散遍历,将所有与其相连的值为‘1’的节点染色,染成2,染色之后这整个岛就会变成2;那么在检测新节点时,只要周围(上下左右)节点都不是2,那么它就是一个新的岛。

代码如下:

package leetCode;

public class Solution {
	
    public int numIslands(char[][] grid) {
        int res = 0;
        
        if(grid.length==0 || grid[0].length==0){
        	return 0;
        }
        
        int row = grid.length;
        int col = grid[0].length;
        
        for(int i=0;i<row;i++){
        	for(int j=0;j<col;j++){
        		if(grid[i][j]=='1'
        				&&(i-1<0 || grid[i-1][j]!='2')
        				&&(j-1<0||grid[i][j-1]!='2') 
        				&&(i+1>=row ||grid[i+1][j]!='2')
        				&&(j+1>=col || grid[i][j+1]!='2')){
        			res++;
        			color(grid,i,j);
        			display(grid);
        			break;
        		}
        	}
        }
        return res;
    }
    
    //从i,j位置开始染色
    public void color(char[][] grid,int i,int j){
    	grid[i][j] = '2';
    	
    	//上
    	if(i-1>=0 && grid[i-1][j]=='1'){
    		color(grid,i-1,j);
    	}
    	//下
    	if(i+1<grid.length && grid[i+1][j]=='1'){
    		color(grid,i+1,j);
    	}
    	//左
    	if(j-1>=0&&grid[i][j-1]=='1'){
    		color(grid,i,j-1);
    	}
    	//右
    	if(j+1<grid[0].length&&grid[i][j+1]=='1'){
    		color(grid,i,j+1);
    	}
    }
	
    public void display(char[][] grid){
    	for(int i=0;i<grid.length;i++){
    		for(int j=0;j<grid[0].length;j++){
    			System.out.print(grid[i][j]+" ");
    		}
    		System.out.println();
    	}
    	System.out.println();
    }
    
    
    public static void main(String[] args) {
    	Solution s = new Solution();
    	
    	//["10111","10101","11101"]
    	char[][] matrix = {
    			{'1','0','1','1','1'},
    			{'1','0','1','0','1'},
    			{'1','1','1','0','1'}
    	};
    	
    	System.out.println(s.numIslands(matrix));
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值