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]);
        }
    }
}

推荐题目

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

相关推荐
每天要多喝水6 天前
图论Day39:孤岛题目
算法·深度优先·图论
仟濹6 天前
【算法打卡day10(2026-02-24 周二)复习算法:DFS BFS 并查集】
算法·深度优先·图论·dfs·bfs·广度优先·宽度优先
Darkwanderor6 天前
数据结构 - 并查集的应用
数据结构·c++·并查集
仰泳的熊猫7 天前
蓝桥杯算法提高VIP-种树
数据结构·c++·算法·蓝桥杯·深度优先·图论
每天要多喝水7 天前
图论Day38:孤岛基础
算法·深度优先·图论
xsyaaaan7 天前
代码随想录Day43图:图论理论基础_深搜理论基础_98所有可达路径_广搜理论基础
图论
WW_千谷山4_sch8 天前
MYOJ_7789:(洛谷P3388)【模板】割点(割顶)(tarjan算法)
c++·算法·深度优先·图论
WW_千谷山4_sch8 天前
MYOJ_11705:(洛谷P1137)旅行计划(经典拓扑排序)
c++·算法·动态规划·图论
yyy(十一月限定版)9 天前
图论——最小生成树Kruskal算法
算法·图论
yyy(十一月限定版)9 天前
图论——最短路Dijkstra算法
算法·图论