求无向图中的连通分量的个数

输入

第一行有两个整数n,m 

n表示有n个点;m表示接下来有m行数据

接下来m行,每行都有两个整数a,b,表示a,b之间有路径

输出

输出无向图中的连通分量的个数

代码

import java.util.LinkedList;
import java.util.Scanner;
public class Main {
    static int n;
    static int m;
    static LinkedList adj[];//邻接链表
    static Scanner cin = new Scanner(System.in);
    public static void main(String[] args) {
        n=cin.nextInt();
        m=cin.nextInt();
        Graph G=new Graph();//邻接链表表示的无向图
        CC cc=new CC(G);//求无向图中的连通分量
        System.out.println(cc.getCount());
        cin.close();
    }
    private static class Graph {
        int V;//点数
        int E;//边数
        public Graph(){
            this.V=n;
            this.E=m;
            adj=new LinkedList[V+1];
           //表示无向图中的点从1开始到V
            for(int i=1;i<V+1;i++){
                adj[i]=new LinkedList<>();
            }
            for(int i=0;i<E;i++){
                int a=cin.nextInt();
                int b=cin.nextInt();
                addEdge(a,b);
            }
        }
        private void addEdge(int a, int b) {
            adj[a].add(b);
            adj[b].add(a);
        }

        public int getV() {
            return V;
        }
        public Iterable<Integer> adj(int v){
            return adj[v];
        }
    }

    private static class CC {
        private boolean marked[];
        private int []id;
        private int count;
        public CC(Graph G) {
            marked=new boolean[G.getV()+1];//默认数组值全为false
            id=new int[G.getV()+1];//默认全为0
            for(int i=1;i<G.getV()+1;i++){
                if(!marked[i]){
                    dfs(G,i);
                    count++;
                }
            }

        }
        private void dfs(Graph G, int i) {
            marked[i]=true;
            id[i]=count;
            for(int k:G.adj(i)){
                if(!marked[k]){
                    dfs(G,k);
                }
            }
        }
        public int getCount() {
            return count;
        }
    }
}
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值