From 1ccadf6ee5fcafa30d6df61e93420f4662b6d10e Mon Sep 17 00:00:00 2001 From: hakyurxinf <96514344+hakyurxinf@users.noreply.github.com> Date: Sat, 27 Jul 2024 14:46:21 +0800 Subject: [PATCH] =?UTF-8?q?Create=20107=E5=AF=BB=E6=89=BE=E5=AD=98?= =?UTF-8?q?=E5=9C=A8=E7=9A=84=E8=B7=AF=E5=BE=84Java=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- 107寻找存在的路径Java代码 | 56 ++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 107寻找存在的路径Java代码 diff --git a/107寻找存在的路径Java代码 b/107寻找存在的路径Java代码 new file mode 100644 index 00000000..7b83ca26 --- /dev/null +++ b/107寻找存在的路径Java代码 @@ -0,0 +1,56 @@ +JAVA: + +```Java + +import java.util.*; + +public class Main{ + public static void main(String[] args) { + int N, M; + Scanner scanner = new Scanner(System.in); + N = scanner.nextInt(); + M = scanner.nextInt(); + DisJoint disJoint = new DisJoint(N + 1); + for (int i = 0; i < M; ++i) { + disJoint.join(scanner.nextInt(), scanner.nextInt()); + } + if(disJoint.isSame(scanner.nextInt(), scanner.nextInt())) { + System.out.println("1"); + } else { + System.out.println("0"); + } + } + +} + +//并查集模板 +class DisJoint{ + private int[] father; + + public DisJoint(int N) { + father = new int[N]; + for (int i = 0; i < N; ++i){ + father[i] = i; + } + } + + public int find(int n) { + return n == father[n] ? n : (father[n] = find(father[n])); + } + + public void join (int n, int m) { + n = find(n); + m = find(m); + if (n == m) return; + father[m] = n; + } + + public boolean isSame(int n, int m){ + n = find(n); + m = find(m); + return n == m; + } + +} + +```