From a0462c4c2539c0b9f65acfc39b32e0bcd9d5a303 Mon Sep 17 00:00:00 2001 From: CH Ye Date: Fri, 15 Sep 2023 16:06:48 -0400 Subject: [PATCH 1/2] =?UTF-8?q?#=20=E6=B7=BB=E5=8A=A0=E4=BA=86=201971.=20?= =?UTF-8?q?=E5=AF=BB=E6=89=BE=E5=9B=BE=E4=B8=AD=E6=98=AF=E5=90=A6=E5=AD=98?= =?UTF-8?q?=E5=9C=A8=E8=B7=AF=E5=BE=84=20=E7=9A=84Python=E5=B9=B6=E6=9F=A5?= =?UTF-8?q?=E9=9B=86=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/1971.寻找图中是否存在路径.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/problems/1971.寻找图中是否存在路径.md b/problems/1971.寻找图中是否存在路径.md index 29e50ab8..5660233c 100644 --- a/problems/1971.寻找图中是否存在路径.md +++ b/problems/1971.寻找图中是否存在路径.md @@ -134,6 +134,22 @@ public: } }; ``` + +PYTHON并查集解法如下: +```PYTHON +class Solution: + def validPath(self, n: int, edges: List[List[int]], source: int, destination: int) -> bool: + p = [i for i in range(n)] + def find(i): + if p[i] != i: + p[i] = find(p[i]) + return p[i] + for u, v in edges: + p[find(u)] = find(v) + return find(source) == find(destination) +``` + +

From 23ca9e43e5a15bdbbf69744515b94736ac1d3b0d Mon Sep 17 00:00:00 2001 From: CH Ye Date: Fri, 15 Sep 2023 16:09:38 -0400 Subject: [PATCH 2/2] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E4=BA=86684.=E5=86=97?= =?UTF-8?q?=E4=BD=99=E8=BF=9E=E6=8E=A5=20=E7=9A=84Python=E5=B9=B6=E6=9F=A5?= =?UTF-8?q?=E9=9B=86=E7=AE=80=E6=B4=81=E5=86=99=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0684.冗余连接.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/problems/0684.冗余连接.md b/problems/0684.冗余连接.md index 8124cc7e..f5e84223 100644 --- a/problems/0684.冗余连接.md +++ b/problems/0684.冗余连接.md @@ -256,6 +256,23 @@ class Solution: return [] ``` +### Python简洁写法: + +```python +class Solution: + def findRedundantConnection(self, edges: List[List[int]]) -> List[int]: + n = len(edges) + p = [i for i in range(n+1)] + def find(i): + if p[i] != i: + p[i] = find(p[i]) + return p[i] + for u, v in edges: + if p[find(u)] == find(v): + return [u, v] + p[find(u)] = find(v) +``` + ### Go ```go