Day55--图论--107. 寻找存在的路径(卡码网)

Day55--图论--107. 寻找存在的路径(卡码网)

今天学习并查集。先过一遍并查集理论基础。再做下面这一道模板题,就可以结束了。体量不多,但是理解并查集,并使用好,不容易。

后续再找相关的题目来做,更新在下方。

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

方法:并查集

思路:

建立并查集类,完成isSame,find和join三个方法。

java 复制代码
import java.util.*;

public class Main {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int m = in.nextInt();
        Disjoint dj = new Disjoint(n);
        for (int i = 0; i < m; i++) {
            int from = in.nextInt();
            int to = in.nextInt();
            dj.join(from, to);
        }
        int source = in.nextInt();
        int destination = in.nextInt();
        if (dj.isSame(source, destination)) {
            System.out.println(1);
        } else {
            System.out.println(0);
        }
    }
}

class Disjoint {
    private int[] father;

    public Disjoint(int n) {
        father = new int[n + 1];
        for (int i = 0; i <= n; i++) {
            father[i] = i;
        }
    }

    public void join(int a, int b) {
        int root1 = find(a);
        int root2 = find(b);
        if (root1 == root2) {
            return;
        }
        father[root2] = root1;
    }

    public boolean isSame(int a, int b) {
        int root1 = find(a);
        int root2 = find(b);
        return root1 == root2;
    }

    public int find(int a) {
        if (a == father[a]) {
            return a;
        } else {
            // return find(father[a]);
            return father[a] = find(father[a]);
        }
    }
}

推荐题目

来自@灵艾山茶府:常用数据结构(前缀和/差分/栈/队列/堆/字典树/并查集/树状数组/线段树)链接中可以搜到并查集相关题目。实际上,可以用并查集做的题目,用其他方法也可以做。

相关推荐
晚枫~39 分钟前
图论基础:探索节点与关系的复杂网络
网络·数据结构·图论
stolentime2 天前
SCP2025T2:P14254 分割(divide) 题解
算法·图论·组合计数·洛谷scp2025
Codeking__3 天前
DFS算法原理及其模板
算法·深度优先·图论
红糖生姜3 天前
P12874 [蓝桥杯 2025 国 Python A] 巡逻||题解||图论
c++·蓝桥杯·图论
PyHaVolask3 天前
数据结构与算法分析
数据结构·算法·图论
Nix Lockhart4 天前
《算法与数据结构》第七章[算法4]:最短路径
c语言·数据结构·学习·算法·图论
CUC-MenG4 天前
2025牛客国庆集训派对day5 K E 个人题解
图论·网络流·状态压缩·随机优化·树上dp·网络流费用流
zc.ovo6 天前
Kruskal重构树
数据结构·c++·算法·重构·图论
qq_574656259 天前
java-代码随想录第66天|Floyd 算法、A * 算法精讲 (A star算法)
java·算法·leetcode·图论
JuneXcy13 天前
C++知识点总结用于打算法
c++·算法·图论