Skip to content

Commit 104be62

Browse files
author
lucifer
committed
feat: 并查集
1 parent a636845 commit 104be62

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

thinkings/union-find.md

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,24 @@ class UF:
196196

197197
- [399. 除法求值](https://leetcode-cn.com/problems/evaluate-division/)
198198

199+
## 应用
200+
201+
- 检测图是否有环
202+
203+
思路: 只需要将边进行合并,并在合并之前判断是否已经联通即可,如果合并之前已经联通说明存在环。
204+
205+
代码:
206+
207+
```py
208+
uf = UF()
209+
for a, b in edges:
210+
if uf.connected(a, b): return False
211+
uf.union(a, b)
212+
return True
213+
```
214+
215+
题目推荐:[Forest Detection](https://binarysearch.com/problems/Forest-Detection)
216+
199217
## 总结
200218

201219
如果题目有连通,等价的关系,那么你就可以考虑并查集,另外使用并查集的时候要注意路径压缩,否则随着树的高度增加复杂度会逐渐增大。

0 commit comments

Comments
 (0)