Merge pull request #2279 from Snow-Ye/master

添加了684.冗余连接 的Python并查集简洁写法 , 添加了 1971. 寻找图中是否存在路径 的Python并查集解法
This commit is contained in:
程序员Carl
2023-09-26 09:36:55 +08:00
committed by GitHub
2 changed files with 33 additions and 0 deletions

View File

@ -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

View File

@ -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)
```
<p align="center">
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>