Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit db09b95

Browse files
Added Cycle Detection
1 parent a78d997 commit db09b95

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

‎graph-theory/cycle_detection.cpp‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/*
2+
***************************
3+
* *
4+
* Author: Swaraj Deep *
5+
* *
6+
***************************
7+
*/
8+
9+
#include <iostream>
10+
#include <vector>
11+
12+
using namespace std;
13+
14+
// Function to detect cycle in the given graph by using dfs. If there is a cycle then there will be a back edge
15+
// We can also generate a cycle (if it exists) by keeping track of each vertex's parent node
16+
bool has_cycle (vector<vector<int>> &graph, vector<bool> &visited, int vertex, int parent) {
17+
visited[vertex] = true;
18+
for (int child: graph[vertex]) {
19+
if (!visited[child]) {
20+
if (has_cycle (graph, visited, child, vertex) == true) {
21+
return true;
22+
}
23+
} else {
24+
if (child != parent) {
25+
return true;
26+
}
27+
}
28+
}
29+
return false;
30+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /