divyanshg10's blog

By divyanshg10, history, 4 years ago, In English

Simply perform a dfs and count the number of nodes visited, if the count increases number of vertices then there is definitely a cycle.

#include<bits/stdc++.h>
using namespace std;
bool vis[100005];
int maxlencyclepossible = 0, tillvisitednode = 0;
void dfs(vector<int> graph[], int node) {
	if (tillvisitednode > maxlencyclepossible) {
		return;
	}
	for (auto child : graph[node]) {
		vis[node] = true;
		tillvisitednode++;
		dfs(graph, child);
	}
	return;
}
void solve() {
	int vert, edge;
	vert = 4, edge = 3;
	memset(vis, false, sizeof(vis));
	vector<int> graph[vert];
	// zero based
	graph[0].push_back(1);
	graph[2].push_back(3);
	graph[3].push_back(2);
	//cycle between 2 and 3
	tillvisitednode = 0;
	maxlencyclepossible = vert + 10;
	tillvisitednode = 0;
	maxlencyclepossible = vert + 10;
	for (int i = 0; i < vert; i++) {
		tillvisitednode = 0;
		if (!vis[i]) {
			dfs(graph, i);
		}
		if (tillvisitednode > maxlencyclepossible) {
			break;
		}
	}
	if (tillvisitednode > maxlencyclepossible) {
		cout << "Cycle Detected\n";
		return;
	}
	cout << "No Cycle Detected\n";
	return ;
}
int main() {
	solve();
	return 0;
}

Full text and comments »

  • Vote: I like it
  • -40
  • Vote: I do not like it