mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
Merge pull request #2279 from Snow-Ye/master
添加了684.冗余连接 的Python并查集简洁写法 , 添加了 1971. 寻找图中是否存在路径 的Python并查集解法
This commit is contained in:
@ -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
|
||||
|
@ -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"/>
|
||||
|
Reference in New Issue
Block a user