From 194a827f8e4a2778084dafcd4e32e58a15e11712 Mon Sep 17 00:00:00 2001 From: mask <1429855087@qq.com> Date: Sun, 22 Oct 2023 11:47:42 +0800 Subject: [PATCH] =?UTF-8?q?Update=201971.=E5=AF=BB=E6=89=BE=E5=9B=BE?= =?UTF-8?q?=E4=B8=AD=E6=98=AF=E5=90=A6=E5=AD=98=E5=9C=A8=E8=B7=AF=E5=BE=84?= =?UTF-8?q?.md=20=E5=A2=9E=E5=8A=A0Java=E8=AF=AD=E8=A8=80=E7=89=88?= =?UTF-8?q?=E6=9C=AC=E9=A2=98=E8=A7=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../1971.寻找图中是否存在路径.md | 58 ++++++++++++++++++- 1 file changed, 57 insertions(+), 1 deletion(-) diff --git a/problems/1971.寻找图中是否存在路径.md b/problems/1971.寻找图中是否存在路径.md index 5660233c..27ee9147 100644 --- a/problems/1971.寻找图中是否存在路径.md +++ b/problems/1971.寻找图中是否存在路径.md @@ -135,7 +135,64 @@ public: }; ``` +## 其他语言版本 + +### Java: + +```java +class Solution { + + int[] father; + public boolean validPath(int n, int[][] edges, int source, int destination) { + father = new int[n]; + init(); + for (int i = 0; i < edges.length; i++) { + join(edges[i][0], edges[i][1]); + } + + return isSame(source, destination); + } + + // 并查集初始化 + public void init() { + for (int i = 0; i < father.length; i++) { + father[i] = i; + } + } + + // 并查集里寻根的过程 + public int find(int u) { + if (u == father[u]) { + return u; + } else { + father[u] = find(father[u]); + return father[u]; + } + } + + // 判断 u 和 v是否找到同一个根 + public boolean isSame(int u, int v) { + u = find(u); + v = find(v); + return u == v; + } + + // 将v->u 这条边加入并查集 + public void join(int u, int v) { + u = find(u); // 寻找u的根 + v = find(v); // 寻找v的根 + if (u == v) return; // 如果发现根相同,则说明在一个集合,不用两个节点相连直接返回 + + father[v] = u; + } + +} +``` + +### Python: + PYTHON并查集解法如下: + ```PYTHON class Solution: def validPath(self, n: int, edges: List[List[int]], source: int, destination: int) -> bool: @@ -154,4 +211,3 @@ class Solution: -