Skip to content

Commit eb1a0f6

Browse files
committed
cycle detection algo is added to graphs
1 parent 2aac4ec commit eb1a0f6

2 files changed

Lines changed: 45 additions & 0 deletions

File tree

‎README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,7 @@ Here are questions divided by difficulty level:
122122
8) [A* Heuristic Path Finding](https://github.com/sherxon/AlgoDS/blob/master/src/algo/graph/AStar.java)
123123
9) [Is Graph Bipartite](https://github.com/sherxon/AlgoDS/blob/master/src/algo/graph/IsBipartite.java)
124124
10) [Is Graph Connected](https://github.com/sherxon/AlgoDS/blob/master/src/algo/graph/IsConnected.java)
125+
11) [Cycle Detection] (https://github.com/sherxon/AlgoDS/blob/master/src/algo/graph/CycleDetection.java)
125126

126127
### String
127128
1) [Rabin Karp Subsequence search](https://github.com/sherxon/AlgoDS/blob/master/src/algo/string/RabinKarpSubsequenceSearch.java)

‎src/algo/graph/CycleDetection.java‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
package algo.graph;
2+
3+
import ds.graph.Graph;
4+
5+
import java.util.HashSet;
6+
import java.util.Set;
7+
8+
/**
9+
* Created by sherxon on 4/16/17.
10+
*/
11+
/**
12+
* To find if the given graph has cycle , We need to maintain one additional set of exited vertices and do dfs.
13+
* In any step if iteration if a vertex is already in visited set and yet not exited from recusion stack, then
14+
* we can return true.
15+
*
16+
* */
17+
public class CycleDetection {
18+
protected Graph graph;
19+
protected Set<Integer> visited;
20+
protected Set<Integer> exited;
21+
22+
public CycleDetection(Graph graph) {
23+
this.graph = graph;
24+
visited=new HashSet<>();
25+
exited=new HashSet<>();
26+
}
27+
28+
public boolean hasCycle(){
29+
return dfs(1);
30+
}
31+
32+
private boolean dfs(Integer start) {
33+
visited.add(start);
34+
35+
for (Integer neighbor : graph.getNeighbors(start)) {
36+
37+
if(visited.contains(neighbor) && !exited.contains(neighbor)) return true;
38+
39+
if(!visited.contains(neighbor) && dfs(neighbor)) return true;
40+
}
41+
exited.add(start);
42+
return false;
43+
}
44+
}

0 commit comments

Comments
 (0)