代码随想录算法训练营第 53 天 | 107. 寻找存在的路径

107. 寻找存在的路径

可用 dfs 或 bfs,这里用并查集。

import java.util.Scanner;

public class Main {
    static int n = 105; // n 根据题目中节点数量而定,一般比节点数量大一点就好
    static int[] father = new int[n];

    static { // 第一次加载类时就会执行
        init();
    }

    // 初始化
    static void init() {
        for (int i = 0; i < n; i++) {
            father[i] = i;
        }
    }

    // 查找根节点(带路径压缩)
    static int find(int a) {
        if (a == father[a]) {
            return a;
        }
        return father[a] = find(father[a]);
    }

    // 将两个元素添加到同一集合(路径压缩法)
    static void join(int a, int b) {
        a  = find(a);
        b = find(b);
        if (a == b) { // 如果本来就在同一集合,直接返回
            return;
        }
        father[a] = b; // 改变的是根的指向
    }

    // 判断两个元素是否在同一集合
    static boolean isSame(int a, int b) {
        a = find(a);
        b = find(b);
        return a == b;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int k = sc.nextInt();
        while (k-- > 0) {
            int s = sc.nextInt();
            int t = sc.nextInt();
            join(s, t);
        }
        int source = sc.nextInt();
        int destination = sc.nextInt();

        System.out.println(isSame(source, destination) ? 1 : 0);
    }
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值