judge loop in undirected graph

时间:2022-10-08 11:13:02

一 深度优先遍历,参考前面DFS(white and gray and black)

二 根据定点以及边数目进行判断

如果m(edge)大于n(vertex),那么肯定存在环

算法如下:

1 删除所有入度小于等于1的顶点, 并且将和这些顶点相关的顶点入度减1

2 将入度变为1的顶点全部删除,重复上述动作,如果最后还有顶点那么图中存在环

具体代码如下:

#include <iostream>
using namespace std; #define MAX_VERTEX_NUM 128
enum color{WHITE, GRAY = 1, BLACK};
bool M[MAX_VERTEX_NUM][MAX_VERTEX_NUM];
int colour[MAX_VERTEX_NUM];
int dfsNum[MAX_VERTEX_NUM], num;
int indegree[MAX_VERTEX_NUM];
int vexnum, edgenum; void init_graph(){
cout<<"enter vertex number:"<<endl;
cin>>vexnum;
cout<<"enter edge number:"<<endl;
cin>>edgenum; int i, j;
while(edgenum){
cout<<"add new edge:"<<endl;
cin>>i>>j;
M[i - 1][j - 1] = true;
//initialize in vertex degree
indegree[i - 1]++;
indegree[j - 1]++;
edgenum--;
}
}
/*
void dfs(int u, int p){
colour[u] = GRAY;
dfsNum[u] = num++;
for( int v = 0; v < vexnum; v++){
if(M[u][v] && v != p){
if(colour[v] == WHITE) dfs(v, u);
else if(colour[v] == GRAY)
cout<<"back edge between"<<u + 1<<" and"<<v + 1<<endl;
else if(colour[v] == BLACK)
cout<<"cross edge between"<<u + 1<<" and"<<v + 1<<endl;;
}
}
colour[u] = BLACK;
}
void print_dfs_num(){
for(int v = 0; v < vexnum; v++)
cout<<dfsNum[v]<<" ";
}
*/ void LoopJudge(){
bool loop = false; int twice = 2;
int k, i, j;
cout<<"line: "<<__LINE__<<endl;
for( k = twice; k > 0; k--){
cout<<"line: "<<__LINE__<<"k: "<<k<<endl;
for( i = 0; i < vexnum; i++){
cout<<"line: "<<__LINE__<<"i: "<<i<<endl;
if(indegree[i] <= 1){
indegree[i] = 0; //delete vertex in degree equal one
for( j = 0; j < vexnum; j++){
cout<<"line: "<<__LINE__<<"j: "<<j<<endl;
if(M[i][j]){
M[i][j] = false;
M[j][i] = false;
indegree[j]--;
}//if(M[i][j])
}//for(int j = 0; j < vexnum; j++)
}//if(indegree[i] <= 1)
}//for(int i = 0; i < vexnum; i++)
} for( k = 0; k < vexnum; k++){
if(indegree[k] != 0){
loop = true;
}
} if(loop)
cout<<"There is loop in undirected graph!"<<endl;
else
cout<<"There is no loop in undirected graph!"<<endl;
} int main()
{
init_graph();
//dfs(0, -1);
//print_dfs_num();
LoopJudge(); int ch;
cin>>ch;
return 0;
}

版权声明:本文为博主原创文章,未经博主允许不得转载。