【发布时间】:2017-12-09 07:05:45
【问题描述】:
所以我有两个功能:
更新
unordered_map<int, bool> visited2;
vector<vector<int>> elements2D;
bool DFSDetectCycle(int vertex){
s.push(vertex);
while(!s.empty()){
int np_vertex = s.top();
s.pop();
if (visited2[np_vertex] == true){
return true;
}
visited2[np_vertex] = true;
for (int i = 0; i<elements2D.size(); i++){
if(elements2D[np_vertex][i] != 0){
if(DFSDetectCycle(i)){
return true;
}
}
}
}
return false;
}
bool hasCycle(vector<vector<int>> v){
if (v.empty()){
return false;
}
for (int i = 0; i<v.size(); i++){
if (!visited2[i]){
if(DFSDetectCycle(i)){
return true;
}
}
}
return false;
}
在我的主要功能中,我这样称呼它:
if (hasCycle(elements2D)){
for (int i = 0; i<elements2D.size(); i++){
if (!visited2[i]){
DFSDetectCycle(i);
}
}
}else{
cout << "No cycles." << endl;
}
所以基本上,输入看起来像这样:
g++ -o GraphProcessor.o GraphProcessor.cpp -std=c++11
./GraphProcessor.o graph1.txt
输出应该是这样的:
Connected components:
{0,1,2,4,7}
{3}
{5,6}
A cycle: 0 1 4 2
但我的输出是这样的:
Connected components:
{0,1,4,2,7}
{3}
{5,6}
No cycles.
graph1.txt 看起来像这样:
0 2 6 0 0 0 0 3
2 0 0 0 4 0 0 1
6 0 0 0 3 0 0 2
0 0 0 0 0 0 0 0
0 4 3 0 0 0 0 0
0 0 0 0 0 0 7 0
0 0 0 0 0 7 0 0
3 1 2 0 0 0 0 0
不要担心连接的组件部分,这不是我现在的问题。我的问题是我的代码没有正确检测图中的循环,也没有正确输出它们。似乎我的 hasCycle() 函数总是给出错误的陈述,但我不确定为什么。 elements2D 是我正在使用的矩阵,因为它是从文件中读取的,所以我需要某个地方来存储它。对于我的visited2 函数,我使用unordered_map 来保留关于我是否访问过顶点的布尔值。我知道如果我再次访问了一个顶点,那么我就有了一个循环。但我不确定如何修改我的算法以获得这样的结果。
再次感谢您的帮助。
【问题讨论】:
-
找到连通分量后是否重置
visited2数组? -
很抱歉,我应该澄清一下。对于连接的组件部分,我使用了一个名为visited 的unordered_map。我为循环初始化了这个名为visited2 的新unordered_map。
标签: c++ graph cycle adjacency-matrix