将有向循环图转换为无环图_无向图中的循环检测

将有向循环图转换为无环图

What you will learn?

您将学到什么?

How to detect a cycle in an undirected graph?

如何检测无向图中的循环?

In the graph below,

在下图中,

Cycle Detection in an Undirected Graph

It has cycles 0-1-4-3-0 or 0-1-2-3-0

它有个周期0-1-4-3-00-1-2-3-0

Algorithm:

算法:

Here we use a recursive method to detect a cycle in a graph.

在这里,我们使用递归方法来检测图中的循环

  1. We check the presence of a cycle starting by each and every node at a time.

    我们检查每个节点每次都开始一个循环的存在。

  2. For each node

    对于每个节点

    1. Whenever we visited one vertex we mark it.
    2. Except for the starting node, we store its parent node go for all its adjacent nodes.
    3. If there is any marked vertex present except parent that means there is a cycle present in the graph.

Function:

功能:

Check(parent , current node){
	visit[curr_node]=true;
	for( all the adjacent vertices ){
		if(not visited yet) then
			check(current node, adjacent vertex);
		else if( the vertex is not the parent) then
			There is a cycle in the graph
	}
}

C++ implementation:

C ++实现:

#include <bits/stdc++.h>
using namespace std;

void addedge(list<int>,int ,int );
void cycle_check(list<int>*,int);

//	Make a pair between vertex x and vertex y
void addedge(list<int> *ls,int x,int y){
	ls[x].push_back(y);
	ls[y].push_back(x);
	return;
} 

void check_cycle_util(list<int> *ls,bool *visit,int curr_node,int parent,int &temp){
	visit[curr_node]=true;
	list<int>::iterator it;
	for(it=ls[curr_node].begin();it!=ls[curr_node].end();it++){
		if(!visit[*it]){
			check_cycle_util(ls,visit,*it,curr_node,temp);
		}
		else if(*it != parent && temp==0){
			temp=1;
			cout<<"There is a cycle in the graph\n";
			break;
		}
	}
}

//checking the cycles in a graph  
void cycle_check(list<int>*ls,int num){
	bool *visit=new bool[num];
	int temp=0;
	for(int i=0;i<num;i++)
		visit[i]=false;
	for(int i=0;i<num;i++){
		if(!visit[i] && temp==0){
			check_cycle_util(ls,visit,i,-2,temp);
		}
	}
}


int main(){
	int num;
	
	cout<<"Enter the no. of vertices :";
	cin>>num;
	
	list<int> *ls=new list<int>[num];
	addedge(ls,0,1);
	addedge(ls,2,3);
	addedge(ls,3,4);
	addedge(ls,4,5);
	addedge(ls,1,2);
	addedge(ls,1,4);
	addedge(ls,3,0);
	cycle_check(ls,6);

	return 0;
}

Output

输出量

Enter the no. of vertices : 6
There is a cycle in the graph


翻译自: https://www.includehelp.com/data-structure-tutorial/cycle-detection-in-an-undirected-graph.aspx

将有向循环图转换为无环图

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值