JavaAlgorithms/DataStructures/Graphs/Cycles.java

88 lines
2.0 KiB
Java
Raw Normal View History

package DataStructures.Graphs;
2018-10-18 18:17:00 +08:00
import java.util.ArrayList;
2020-10-24 18:23:28 +08:00
import java.util.Scanner;
2018-10-18 18:17:00 +08:00
class Cycle {
2020-10-24 18:23:28 +08:00
private int nodes, edges;
private int[][] adjacencyMatrix;
private boolean[] visited;
ArrayList<ArrayList<Integer>> cycles = new ArrayList<ArrayList<Integer>>();
2018-10-18 18:17:00 +08:00
2020-10-24 18:23:28 +08:00
public Cycle() {
Scanner in = new Scanner(System.in);
System.out.print("Enter the no. of nodes: ");
nodes = in.nextInt();
System.out.print("Enter the no. of Edges: ");
edges = in.nextInt();
2018-10-18 18:17:00 +08:00
2020-10-24 18:23:28 +08:00
adjacencyMatrix = new int[nodes][nodes];
visited = new boolean[nodes];
2018-10-18 18:17:00 +08:00
2020-10-24 18:23:28 +08:00
for (int i = 0; i < nodes; i++) {
visited[i] = false;
}
2018-10-18 18:17:00 +08:00
2020-10-24 18:23:28 +08:00
System.out.println("Enter the details of each edges <Start Node> <End Node>");
2018-10-18 18:17:00 +08:00
2020-10-24 18:23:28 +08:00
for (int i = 0; i < edges; i++) {
int start, end;
start = in.nextInt();
end = in.nextInt();
adjacencyMatrix[start][end] = 1;
2018-10-18 18:17:00 +08:00
}
2020-10-24 18:23:28 +08:00
in.close();
}
public void start() {
for (int i = 0; i < nodes; i++) {
ArrayList<Integer> temp = new ArrayList<>();
dfs(i, i, temp);
for (int j = 0; j < nodes; j++) {
adjacencyMatrix[i][j] = 0;
adjacencyMatrix[j][i] = 0;
}
2018-10-18 18:17:00 +08:00
}
2020-10-24 18:23:28 +08:00
}
private void dfs(Integer start, Integer curr, ArrayList<Integer> temp) {
temp.add(curr);
visited[curr] = true;
for (int i = 0; i < nodes; i++) {
if (adjacencyMatrix[curr][i] == 1) {
if (i == start) {
cycles.add(new ArrayList<Integer>(temp));
} else {
if (!visited[i]) {
dfs(start, i, temp);
}
2018-10-18 18:17:00 +08:00
}
2020-10-24 18:23:28 +08:00
}
2018-10-18 18:17:00 +08:00
}
2020-10-24 18:23:28 +08:00
if (temp.size() > 0) {
temp.remove(temp.size() - 1);
2018-10-18 18:17:00 +08:00
}
2020-10-24 18:23:28 +08:00
visited[curr] = false;
}
public void printAll() {
for (int i = 0; i < cycles.size(); i++) {
for (int j = 0; j < cycles.get(i).size(); j++) {
System.out.print(cycles.get(i).get(j) + " -> ");
}
System.out.println(cycles.get(i).get(0));
System.out.println();
}
}
2018-10-18 18:17:00 +08:00
}
public class Cycles {
2020-10-24 18:23:28 +08:00
public static void main(String[] args) {
Cycle c = new Cycle();
c.start();
c.printAll();
}
}