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

推荐题目

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

相关推荐
钮钴禄·爱因斯晨21 小时前
数据结构|图论:从数据结构到工程实践的核心引擎
c语言·数据结构·图论
heeheeai2 天前
kotlin图算法
算法·kotlin·图论
杨小码不BUG4 天前
CSP-J/S初赛知识点精讲-图论
c++·算法·图论··编码·csp-j/s初赛
(❁´◡`❁)Jimmy(❁´◡`❁)5 天前
【Trie】 UVA1401 Remember the Word
算法·word·图论
qq_418247886 天前
论文阅读:TEMPORAL GRAPH NETWORKS FOR DEEP LEARNING ON DYNAMIC GRAPHS
论文阅读·人工智能·深度学习·图论
希望201715 天前
图论基础知识
算法·图论
行走的bug...16 天前
用图论来解决问题
算法·图论
Athenaand16 天前
代码随想录算法训练营第50天 | 图论理论基础、深搜理论基础、98. 所有可达路径、广搜理论基础
算法·图论
_Coin_-17 天前
算法训练营DAY60 第十一章:图论part11
算法·图论
Athenaand17 天前
代码随想录算法训练营第62天 | Floyd 算法精讲、A * 算法精讲 (A star算法)、最短路算法总结篇、图论总结
算法·图论