繁体   English   中英

图:如何使用 DFS 检测无向图中的循环

[英]Graph: How to detect cycles in a undirectd graph using DFS

以下是我的 DFS 实现,现在我想实现它,以便我可以检测图中是否存在任何循环。(以下代码基本上用于查找连接元素的数量)

#include <iostream>
#include <vector>
using namespace std;

vector <int> adj[10];
int visited[10];
bool flag=false;

void dfs(int s) {
    visited[s] = 0;
    for(int i = 0;i < adj[s].size();++i)    {
     if(visited[adj[s][i]] == -1)
         dfs(adj[s][i]);
     else if (visited[adj[s][i]] ==1){
        flag=true;
        // cout<<"g";  
        return;
     }
    }
    visited[s]=1;
}

void initialize() {
    for(int i = 0;i < 10;++i)
     visited[i] = -1;
}

int main() {
    int nodes, edges, x, y ;
    cin >> nodes;                       //Number of nodes
    cin >> edges;                       //Number of edges
    for(int i = 0;i < edges;++i) {
     cin >> x >> y;     
     adj[x].push_back(y);                   //Edge from vertex x to vertex y
     adj[y].push_back(x);                   //Edge from vertex y to vertex x
    }

    initialize();                           //Initialize all nodes as not visited

    for(int i = 1;i <= nodes;++i) {
     if(visited[i] == false)     {
         dfs(i);
     }

    }
    if (flag)
        cout<<"Graph contains cycles"<<endl;
    else
        cout<<"No cycles"<<endl;
    return 0;
}

我不确定如何实现它,任何人都可以帮助我。

编辑:我试图实现它。 不知道我哪里错了

我在初始化调用后将循环更改为:

for(int i = 0;i < nodes;++i) {
  if(visited[i] == -1)     {
    dfs(i);
  }
}

您的代码没有开始检查,因为visited每个元素都设置为-1 ,因此被跳过。 因此,通过此更改它确实有效。

我建议查看全局变量adjvisted大小,如果可能,将它们设为本地变量。 当输入 11 个或更多节点时,此代码将停止工作。

编辑问题“你能告诉我如何检查断开连接的图形吗?”

将相同的循环更改为:

int nr_of_graphs = 0;
for(int i = 0;i < nodes;++i) {
  if(visited[i] == -1)     {
    ++nr_of_graphs;
    dfs(i);
  }
}
cout << "Nr of disconnected subgraphs " << nr_of_graphs << endl; 

为每个尚未访问的节点调用dfs(i) 所以计算从 main 调用这个函数的次数,给出断开连接的子图的数量。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM