I have referred to this for what constitutes as an Euler Cycle: https://xlinux.nist.gov/dads/HTML/eulercycle.html
This assignment required me to use Depth First Search and have the methods I have included. I am also required to use the Graph class provided here: https://algs4.cs.princeton.edu/code/edu/princeton/cs/algs4/Graph.java.html
I have tested and in my eyes, it works well. Code wise, I feel like it has a lot to improve hence I am here to ask for simple/general advice.
import edu.princeton.cs.algs4.GraphGenerator;
import java.util.ArrayList;
import java.util.LinkedList;
public class EulerFinder {
private Graph g;
private boolean[] visited;
private ArrayList<Integer> order = new ArrayList<>();
public EulerFinder(Graph g) {
System.out.println("og graph for reference:\n");
System.out.println(g);
System.out.println("------------------------------");
this.g = g;
visited = new boolean[g.E()];
if (hasCycle(g)) {
System.out.println("The cycle for the generated graph is: ");
for (int vertex : verticesInCycle()) {
System.out.println(vertex);
}
} else {
System.out.println("No Euler cycle could be found");
}
}
public static void main(String[] args) {
Graph graph1 = new Graph(4);
graph1.addEdge(3, 1);
graph1.addEdge(1, 0);
graph1.addEdge(0, 2);
graph1.addEdge(2, 3);
//Graph graph = GraphGenerator.eulerianCycle(5, 5);
EulerFinder result = new EulerFinder(graph1);
}
public boolean hasCycle(Graph g) {
if (!evenDegree(g))
return false;
return true;
}
private boolean evenDegree(Graph g) {
for(int i = 0; i < g.V(); i++) {
if(g.degree(i) %2 != 0)
return false;
}
return true;
}
private void DFS(int vertex) {
order.add(vertex);
visited[vertex] = true;
Iterable<Integer> next = g.adj(vertex);
for (int adj : next) {
if(!visited[adj]) {
DFS(adj);
}
}
}
public ArrayList<Integer> verticesInCycle() {
if (g.E() > 0) {
DFS(g.E() - 1);
} else
System.out.println("\nNone! There must be more than 0 edges...");
return order;
}
}
the output for the above example (from main) yields:
og graph for reference:
4 vertices, 4 edges
0: 2 1
1: 0 3
2: 3 0
3: 2 1
------------------------------
The cycle for the generated graph is:
3
2
0
1
Process finished with exit code 0```