Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

[pull] master from youngyangyang04:master #456

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
pull merged 5 commits into AlgorithmAndLeetCode:master from youngyangyang04:master
Jun 12, 2024
Merged
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 21 additions & 3 deletions problems/1971.寻找图中是否存在路径.md
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -38,11 +38,22 @@ void init() {
father[i] = i;
}
}
// 并查集里寻根的过程
// 并查集里寻根的过程,这里递归调用当题目数据过多,递归调用可能会发生栈溢出

int find(int u) {
return u == father[u] ? u : father[u] = find(father[u]); // 路径压缩
}

// 使用迭代的方法可以避免栈溢出问题
int find(int x) {
while (x != parent[x]) {
// 路径压缩,直接将x链接到其祖先节点,减少树的高度
parent[x] = parent[parent[x]];
x = parent[x];
}
return x;
}

// 判断 u 和 v是否找到同一个根
bool isSame(int u, int v) {
u = find(u);
Expand Down Expand Up @@ -75,6 +86,8 @@ void join(int u, int v) {

此时我们就可以直接套用并查集模板。

本题在join函数调用find函数时如果是递归调用会发生栈溢出提示,建议使用迭代方法

使用 join(int u, int v)将每条边加入到并查集。

最后 isSame(int u, int v) 判断是否是同一个根 就可以了。
Expand All @@ -93,8 +106,13 @@ private:
}
}
// 并查集里寻根的过程
int find(int u) {
return u == father[u] ? u : father[u] = find(father[u]);
int find(int x) {
while (x != parent[x]) {
// 路径压缩,直接将x链接到其祖先节点,减少树的高度
parent[x] = parent[parent[x]];
x = parent[x];
}
return x;
}

// 判断 u 和 v是否找到同一个根
Expand Down

AltStyle によって変換されたページ (->オリジナル) /