File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -122,6 +122,7 @@ Here are questions divided by difficulty level:
1221228 ) [ A* Heuristic Path Finding] ( https://github.com/sherxon/AlgoDS/blob/master/src/algo/graph/AStar.java )
1231239 ) [ Is Graph Bipartite] ( https://github.com/sherxon/AlgoDS/blob/master/src/algo/graph/IsBipartite.java )
12412410 ) [ 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
1271281 ) [ Rabin Karp Subsequence search] ( https://github.com/sherxon/AlgoDS/blob/master/src/algo/string/RabinKarpSubsequenceSearch.java )
Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments