SWUST OJ 1076: C++ implementation of judging whether a given directed graph has a loop

topic description

Determines whether a given directed graph has a cycle.

enter

The first line is the number n of vertices in the graph; the second line is the number e of arcs on the way; the third line is vertex information; and then e line is the two vertices to which e arcs are attached.

output

#include<bits/stdc++.h>
using namespace std;
int m, n, g = 0, a[105];
char s[105];
vector<char>v[105];
void dfs(char c1, char c2){
	if(g) return;
	if(c2==c1&&a[c2]){
		g++;
		return;
	}
	for(auto i:v[c2]){
		if(!a[i]){
			a[i]++;
			dfs(c1, i);
			a[i]--;
		}
	}
}
int main(){
	cin>>m>>n;
	for(int i = 0; i < n; i++) cin>>s[i];
	for(int i = 0; i < m; i++){
		char c1, c2;
		cin>>c1>>c2;
		v[c1].push_back(c2);
	}
	for(int i = 0; i < n; i++){
		dfs(s[i], s[i]);
		if(g) break;
	}
	cout<<((g==0)?"no":"yes");
	return 0;
}

Whether there is a loop in the graph is the output yes , not the output no .

 

Guess you like

Origin blog.csdn.net/Ljy_Cxy/article/details/131471922