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

1.卡码网 107. 寻找存在的路径

题目链接:https://kamacoder.com/problempage.php?pid=1179
文章链接:https://www.programmercarl.com/kamacoder/0107.寻找存在的路径.html

在这里插入图片描述
思路:
题目中各个点是双向图链接,那么判断 一个顶点到另一个顶点有没有有效路径其实就是看这两个顶点是否在同一个集合里。
如何算是同一个集合呢,有边连在一起,就算是一个集合。
使用 join(int u, int v)将每条边加入到并查集。
最后 isSame(int u, int v) 判断是否是同一个根 就可以了。

import java.util.*;

public class Main {
    static int[] father = null;
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int m = sc.nextInt();
        father = new int[n+1];
        init(father);
        for (int i=0;i<m;i++) {
            int u = sc.nextInt();
            int v = sc.nextInt();
            join(u,v);
        }
        int source = sc.nextInt();
        int destination = sc.nextInt();
        
        System.out.println(isSame(source,destination));
    }
    
    // 初始化father
    public static void init(int[] father) {
        for (int i=0;i<father.length;i++) {
            father[i]=i;
        }
    }
    
    // 寻找根节点
    public static int find(int u) {
        if (u==father[u]) return u;
        return father[u] = find(father[u]);
    }
    // 添加
    public static void join(int u,int v) {
        u = find(u);
        v = find(v);
        if (u==v) return;
        father[v]=u;
    }
    
    public static int isSame(int u,int v) {
        u = find(u);
        v = find(v);
        return u == v ? 1:0;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值