Skip to content

Commit f771b8b

Browse files
authored
Merge pull request TheAlgorithms#589 from shivg7706/cycle
all cycles present in a graph
2 parents 24eadc6 + 5eaa579 commit f771b8b

File tree

1 file changed

+89
-0
lines changed

1 file changed

+89
-0
lines changed

DataStructures/Graphs/Cycles.java

+89
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
import java.util.Scanner;
2+
import java.util.ArrayList;
3+
4+
5+
class Cycle {
6+
7+
private int nodes, edges;
8+
private int [][] adjacencyMatrix;
9+
private boolean [] visited;
10+
ArrayList<ArrayList<Integer>> cycles = new ArrayList<ArrayList<Integer>>();
11+
private boolean [] finalCycles;
12+
13+
public Cycle() {
14+
Scanner in = new Scanner(System.in);
15+
System.out.print("Enter the no. of nodes: ");
16+
nodes = in.nextInt();
17+
System.out.print("Enter the no. of Edges: ");
18+
edges = in.nextInt();
19+
20+
adjacencyMatrix = new int [nodes][nodes];
21+
visited = new boolean [nodes];
22+
23+
for (int i = 0; i < nodes; i++) {
24+
visited[i] = false;
25+
}
26+
27+
System.out.println("Enter the details of each edges <Start Node> <End Node>");
28+
29+
for(int i = 0; i < edges; i++) {
30+
int start, end;
31+
start = in.nextInt();
32+
end = in.nextInt();
33+
adjacencyMatrix[start][end] = 1;
34+
}
35+
36+
}
37+
38+
public void start() {
39+
for (int i = 0; i < nodes; i++) {
40+
ArrayList<Integer> temp = new ArrayList<>();
41+
dfs(i, i, temp);
42+
for (int j = 0; j < nodes; j++) {
43+
adjacencyMatrix[i][j] = 0;
44+
adjacencyMatrix[j][i] = 0;
45+
}
46+
}
47+
}
48+
49+
private void dfs(Integer start, Integer curr, ArrayList<Integer> temp) {
50+
temp.add(curr);
51+
visited[curr] = true;
52+
for (int i = 0; i < nodes; i++) {
53+
if(adjacencyMatrix[curr][i] == 1) {
54+
if (i == start) {
55+
cycles.add(new ArrayList<Integer>(temp));
56+
} else {
57+
if (!visited[i]) {
58+
dfs(start, i, temp);
59+
}
60+
}
61+
}
62+
}
63+
64+
if(temp.size() > 0) {
65+
temp.remove(temp.size() - 1);
66+
}
67+
visited[curr] = false;
68+
}
69+
70+
public void printAll() {
71+
for (int i = 0; i < cycles.size(); i++) {
72+
for (int j = 0; j < cycles.get(i).size(); j++) {
73+
System.out.print(cycles.get(i).get(j) + " -> ");
74+
}
75+
System.out.println(cycles.get(i).get(0));
76+
System.out.println();
77+
}
78+
79+
}
80+
81+
}
82+
83+
public class Cycles {
84+
public static void main(String[] args) {
85+
Cycle c = new Cycle();
86+
c.start();
87+
c.printAll();
88+
}
89+
}

0 commit comments

Comments
 (0)