图的连通分量(岛屿数量)

在这里插入图片描述

import java.util.Scanner;
import java.util.Arrays;

public class Main2{
	private static int color[],map[][];
	private static int count,N;

	public static void main(String[] args){
		Scanner sc = new Scanner(System.in);
		//while(sc.hasNext()){
			N = sc.nextInt();//图的结点个数
			map = new int[N][N];
			color = new int[N+1];
			Arrays.fill(color,-1);
			for(int i=0;i<N;i++){
				for(int j=0;j<N;j++){
					map[i][j] = sc.nextInt();
				}
			}
			countNum();
			System.out.println(count);
		//}
	}

	public static void countNum(){
		for(int i=0;i<N;i++){
			if(color[i]==-1){
				dfs(i);
				count++;
			}
		}
	}

	//对一个连通分量中的点进行标记,染色
	private static void dfs(int i){
		color[i] = count;
		for(int k = 0;k < map[i].length;k++){
			if(color[k] == -1 && map[i][k] == 1){
				dfs(k);
			}
		}
	}
}

测试例:
0 1 1 0 0 1 1 0 0 0 0 0 0
1 0 0 0 0 0 0 0 0 0 0 0 0
1 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 1 1 0 0 0 0 0 0 0
0 0 0 1 0 1 1 0 0 0 0 0 0
1 0 0 1 1 0 0 0 0 0 0 0 0
1 0 0 0 1 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 1 0 0 0 0
0 0 0 0 0 0 0 1 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 1 1 1
0 0 0 0 0 0 0 0 0 1 0 0 0
0 0 0 0 0 0 0 0 0 1 0 0 1
0 0 0 0 0 0 0 0 0 1 0 1 0
在这里插入图片描述
——连通分量个数为3个!

代码参考来源

【岛屿数量】——LeetCode200

给你一个由 ‘1’(陆地)和 ‘0’(水)组成的的二维网格,请你计算网格中岛屿的数量。
岛屿总是被水包围,并且每座岛屿只能由水平方向或竖直方向上相邻的陆地连接形成。
此外,你可以假设该网格的四条边均被水包围。
示例 1:

输入:
11110
11010
11000
00000
输出: 1

示例2:

输入:
11000
11000
00100
00011
输出: 3
解释: 每座岛屿只能由水平和/或竖直方向上相邻的陆地连接而成。

public class Solution{
	//定义在方法之外,是为了不同的方法调用这些,不用传参,而显得方法体复杂
	static final int[][] directions = {{-1,0},{0,-1},{1,0},{0,1}};//方向数组:四个方向的坐标偏移量
	boolean[][] marked;	//标记数组:标记格子是否被访问过
	int rows;//行数
	int cols;//列数
	char[][] grid;//邻接矩阵

	public int numIslands(char[][] grid) {
		rows = grid.length;
		if(rows==0) return 0;
		cols = grid[0].length;
        //引用grid定义在了方法外面,如果不加this,就默认为初始化值,而不是传入的grid
		this.grid = grid;
		marked = new boolean[rows][cols];
		int count = 0;//岛屿数量
		for(int i = 0;i < rows;i++){
			for(int j = 0;j < cols;j++){
				//如果是陆地,且没有被访问过
				if(!marked[i][j] && grid[i][j] == '1'){
					count++;
					dfs(i,j);
				}
			}
		}
		return count;
	}
	private void dfs(int i,int j){
		marked[i][j] = true;
		for(int k = 0;k < 4;k++){
			int newX = i + directions[k][0];//四个方法逐个试探,dfs
			int newY = j + directions[k][1];
			//如果没有越界,没有被访问过,还是陆地,就递归dfs
            if (inArea(newX, newY) && grid[newX][newY] == '1' && !marked[newX][newY]) {
				dfs(newX,newY);
			}
		}
	}
	//判断是否越界
	private boolean inArea(int x,int y){
		return x >= 0 && x <rows && y>=0 && y < cols;
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值