From 9a778586f398a0c807a4469410936c573bc2e6ef Mon Sep 17 00:00:00 2001 From: Gianluca <gianlucamastrolonardo10@gmail.com> Date: Mon, 29 Apr 2024 21:31:37 +0200 Subject: [PATCH] fixed Lab5 --- Algoritmi_2/Laboratorio/Lab5/Test/TestLab.java | 5 ++++- Algoritmi_2/Laboratorio/Lab5/src/DFS.java | 18 ++++++++---------- 2 files changed, 12 insertions(+), 11 deletions(-) diff --git a/Algoritmi_2/Laboratorio/Lab5/Test/TestLab.java b/Algoritmi_2/Laboratorio/Lab5/Test/TestLab.java index a058fc4..7aaaf0d 100644 --- a/Algoritmi_2/Laboratorio/Lab5/Test/TestLab.java +++ b/Algoritmi_2/Laboratorio/Lab5/Test/TestLab.java @@ -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()); diff --git a/Algoritmi_2/Laboratorio/Lab5/src/DFS.java b/Algoritmi_2/Laboratorio/Lab5/src/DFS.java index a5a2aa7..4dd95fc 100644 --- a/Algoritmi_2/Laboratorio/Lab5/src/DFS.java +++ b/Algoritmi_2/Laboratorio/Lab5/src/DFS.java @@ -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; -- GitLab