mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 08:50:15 +08:00
Merge pull request #2314 from Maskvvv/master
Update 1971.寻找图中是否存在路径.md 增加Java语言版本题解
This commit is contained in:
@ -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:
|
||||
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
||||
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
|
||||
</a>
|
||||
|
||||
|
Reference in New Issue
Block a user