Skip to content
Snippets Groups Projects
Commit 9a778586 authored by Gianluca's avatar Gianluca
Browse files

fixed Lab5

parent 4f596e42
No related branches found
No related tags found
No related merge requests found
......@@ -72,11 +72,14 @@ class TestLab {
DFS dfsTest = new DFS(dag);
Assertions.assertTrue(dfsTest.topologicalOrderDag().indexOf(0) < dfsTest.topologicalOrder().indexOf(3));
System.out.println(dfsTest.hasDirCycle());
DirectedGraph cyclicGraph = new DirectedGraph("3; 0 1; 1 2; 2 0");
DFS dfsCyclicTest = new DFS(cyclicGraph);
System.out.println(dfsCyclicTest.hasDirCycle());
Assertions.assertThrows(IllegalArgumentException.class, () -> dfsCyclicTest.topologicalOrderDag());
//Da sistemare, bisogna usare ordine fine visita invece che array di padri (per grafi orientati)
// Ora funziona anche con questo grafo
DirectedGraph cyclicGraph2 = new DirectedGraph("2; 0 1; 1 0;");
DFS dfsCyclicTest2 = new DFS(cyclicGraph2);
Assertions.assertThrows(IllegalArgumentException.class, () -> dfsCyclicTest2.topologicalOrderDag());
......
......@@ -12,7 +12,7 @@ class DFS {
private GraphInterface myGraph;
private boolean[] founded;
private GraphInterface treeDFS;
private int[] fathers;
private ArrayList<Integer> terminated = new ArrayList<>();
private ArrayList<Integer> postVisitOrder = new ArrayList<>();
......@@ -66,16 +66,16 @@ class DFS {
private
boolean hasDirCycleImpl(int sorg) {
founded[sorg] = true;
for (Integer node : myGraph.getNeighbors(sorg)) {
if (!founded[node]) {
fathers[node] = sorg;
if (hasDirCycleImpl(node)) {
return true;
for (int neighbour : myGraph.getNeighbors(sorg)) {
if (!founded[neighbour]) {
if (hasDirCycleImpl(neighbour)) { // Check the result of the recursive call
return true; // If a cycle is detected in the recursive call, propagate it up
}
} else if (fathers[sorg] != -1 && node != fathers[sorg]) {
} else if (!terminated.contains(neighbour)) {
return true;
}
}
terminated.add(sorg);
return false;
}
......@@ -85,9 +85,7 @@ class DFS {
throw new IllegalArgumentException("Impossibile usare hasDirCycle su un grafo non orientato");
}
for (int i = 0; i < myGraph.getOrder(); i++) {
fathers = new int[myGraph.getOrder()];
Arrays.fill(fathers, -1);
founded = new boolean[myGraph.getOrder()];
terminated.clear();
Arrays.fill(founded, false);
if (hasDirCycleImpl(i)) {
return true;
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment