【发布时间】:2020-07-09 06:42:07
【问题描述】:
这是我的代码在无向图中进行循环检测
#include<iostream>
#include <list>
#include <vector>
#include <stack>
using namespace std;
class Graph {
int V, index;
const int N = 100000;
list <int> * adj;
vector<bool> visited;
// parent stores the parent node of the visited node, this is used
// for finding cycle in an undirected graph
vector<int> parent;
bool isCycle;
public:
Graph(int V);
~Graph () {
delete [] adj;
}
void addEdge(int src, int dst);
void set_index();
void DFS_isCycleUntil(int src);
bool IsCyclePresent();
void printCycles(int edges, int mark[], int& cyclenumber);
};
Graph::Graph(int V){
this->V = V;
adj = new list<int> [V];
this->index = 0;
visited.resize(V, false);
parent.resize(V, -1);
isCycle = false;
}
void Graph::set_index()
{
this->index = 0;
}
void Graph::addEdge(int src, int dst) {
adj[src].push_back(dst); // push back to add to the linked list
adj[dst].push_back(src);
}
void Graph::DFS_isCycleUntil(int src) {
visited[src] = true;
for (auto& adj_V: adj[src]) {
if (!visited[adj_V]) {
parent[adj_V]=src;
DFS_isCycleUntil(adj_V);
} else if(parent[src] != adj_V) {
isCycle = true;
return;
}
}
}
bool Graph::IsCyclePresent() {
return isCycle;
}
int main()
{
Graph gdfs(6);
gdfs.addEdge(0, 1);
gdfs.addEdge(1, 2);
gdfs.addEdge(2, 3);
gdfs.addEdge(3, 4);
gdfs.addEdge(4, 5);
gdfs.addEdge(5, 2);
gdfs.DFS_isCycleUntil(0);
cout << " Depth-first traversal for the given graph: "<<endl;
cout << "cycle present: " << (gdfs.IsCyclePresent() ? "true" : "false")<< '\n';
return 0;
}
我想打印出每个检测到的周期。我已经看到了 geekforgeek 的一些尝试,但恐怕我无法遵循它......这可能是错误的。 我想知道任何人都可以提出一种有效的方法来包含一个打印功能来打印出所有检测到的循环的路径?
【问题讨论】:
-
你使用什么算法进行周期检测?
-
DFS...应该很快。
-
我看到了 geeksforgeeks 的一些尝试:请在此处链接
-
你卡在哪里了?很简单
标签: c++ graph-algorithm