Skip to content

Commit b5b2aa3

Browse files
authored
Update 0107.寻找存在的路径.md for python and go
Update 0107.寻找存在的路径.md for python and go
1 parent f16c640 commit b5b2aa3

File tree

1 file changed

+119
-0
lines changed

1 file changed

+119
-0
lines changed

problems/kamacoder/0107.寻找存在的路径.md

Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -217,8 +217,127 @@ class DisJoint{
217217

218218
### Python
219219

220+
```python
221+
222+
class UnionFind:
223+
def __init__(self, size):
224+
self.parent = list(range(size + 1)) # 初始化并查集
225+
226+
def find(self, u):
227+
if self.parent[u] != u:
228+
self.parent[u] = self.find(self.parent[u]) # 路径压缩
229+
return self.parent[u]
230+
231+
def union(self, u, v):
232+
root_u = self.find(u)
233+
root_v = self.find(v)
234+
if root_u != root_v:
235+
self.parent[root_v] = root_u
236+
237+
def is_same(self, u, v):
238+
return self.find(u) == self.find(v)
239+
240+
241+
def main():
242+
import sys
243+
input = sys.stdin.read
244+
data = input().split()
245+
246+
index = 0
247+
n = int(data[index])
248+
index += 1
249+
m = int(data[index])
250+
index += 1
251+
252+
uf = UnionFind(n)
253+
254+
for _ in range(m):
255+
s = int(data[index])
256+
index += 1
257+
t = int(data[index])
258+
index += 1
259+
uf.union(s, t)
260+
261+
source = int(data[index])
262+
index += 1
263+
destination = int(data[index])
264+
265+
if uf.is_same(source, destination):
266+
print(1)
267+
else:
268+
print(0)
269+
270+
if __name__ == "__main__":
271+
main()
272+
273+
274+
```
275+
276+
220277
### Go
221278

279+
```go
280+
281+
package main
282+
283+
import (
284+
"fmt"
285+
)
286+
287+
const MaxNodes = 101
288+
289+
var n int
290+
var father [MaxNodes]int
291+
292+
// 初始化并查集
293+
func initialize() {
294+
for i := 1; i <= n; i++ {
295+
father[i] = i
296+
}
297+
}
298+
299+
// 并查集里寻根的过程
300+
func find(u int) int {
301+
if u == father[u] {
302+
return u
303+
}
304+
father[u] = find(father[u])
305+
return father[u]
306+
}
307+
308+
// 判断 u 和 v 是否找到同一个根
309+
func isSame(u, v int) bool {
310+
return find(u) == find(v)
311+
}
312+
313+
// 将 v->u 这条边加入并查集
314+
func join(u, v int) {
315+
rootU := find(u)
316+
rootV := find(v)
317+
if rootU != rootV {
318+
father[rootV] = rootU
319+
}
320+
}
321+
322+
func main() {
323+
var m, s, t, source, destination int
324+
fmt.Scan(&n, &m)
325+
initialize()
326+
for i := 0; i < m; i++ {
327+
fmt.Scan(&s, &t)
328+
join(s, t)
329+
}
330+
fmt.Scan(&source, &destination)
331+
if isSame(source, destination) {
332+
fmt.Println(1)
333+
} else {
334+
fmt.Println(0)
335+
}
336+
}
337+
338+
339+
```
340+
222341
### Rust
223342

224343
### Javascript

0 commit comments

Comments
 (0)