[英]Detect a cycle and also get the members of the cycle in an Undirected Graph
我试图找出无向图是否有循环。 如果它确实有一个循环,则获取循环的成员。
我知道获取所有循环要困难得多,但我想知道何时检测到循环,我可以获取该循环的成员。
bool isThereACycle()
{
std::stack<std::pair<int, int>> mystack;
mystack.push(std::make_pair(0, -1));
std::vector<bool> visited(N, false); // N is the number of nodes
visited[0] = true;
while (!mystack.empty()) {
int v = mystack.top().first;
int f = mystack.top().second; // parent node
mystack.pop();
auto& edges = adj[v];
for (auto it = edges.begin(); it != edges.end(); it++)
{
int w = *it;
if (!visited[w])
{
mystack.push(std::make_pair(w, v));
visited[w] = true;
} else if (w != f)
{
return true;
}
}
}
return false;
}
上面的代码检测到循环,但我无法找到与循环关联的成员。 有没有办法稍微修改它以要求获取成员?
是的。 如果您存储每个节点的父节点,并且当您找到一个循环时,只需将 go 向后,而您没有到达找到循环的点。 解决方案的另一部分是,如果您在外部 while 中处理它,则设置访问的节点。
bool isThereACycle()
{
std::stack<std::pair<int, int>> mystack;
mystack.push(std::make_pair(0, -1));
std::vector<bool> visited(N, false); // N is the number of nodes
std::vector<int> parent(N, -1);
while (!mystack.empty()) {
int v = mystack.top().first;
int f = mystack.top().second; // parent node
visited[v] = true;
mystack.pop();
auto& edges = adj[v];
int szamlalo = 0;
for (auto it = edges.begin(); it != edges.end(); it++, szamlalo++)
{
int w = *it;
if (!visited[w])
{
mystack.push(std::make_pair(w, v));
parent[w] = v;
} else if (w != f)
{
int current = v;
while(current != w){
result.push_back(current);
current = parent[current];
mystack.pop();
}
result.push_back(current);
return true;
}
}
}
return false;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.