From a3d28d9ea91f90af072066b2a77030e929ab0f0e Mon Sep 17 00:00:00 2001 From: Haidong Ji Date: Wed, 20 May 2020 18:37:36 -0500 Subject: Check if DAG (Directed Acyclic Graph) done. In the exercise it's Checking Consistency of CS Curriculum. For the clock variable to assign pre-visit and post-visit values, I used a trick of defining the clock as int[1], so its mutable and I can increment it. I don't know if that's a best practice, but for now I'm happy that the program is good. Fun stuff! --- src/main/Acyclicity.java | 59 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 src/main/Acyclicity.java (limited to 'src/main') diff --git a/src/main/Acyclicity.java b/src/main/Acyclicity.java new file mode 100644 index 0000000..1d69ab8 --- /dev/null +++ b/src/main/Acyclicity.java @@ -0,0 +1,59 @@ +import java.util.ArrayList; +import java.util.Scanner; + +public class Acyclicity { + static int acyclic(ArrayList> adj) { + ArrayList visited = new ArrayList<>(); + int[] prev = new int[adj.size()]; + int[] postv = new int[adj.size()]; + int[] clock = new int[1]; + clock[0] = 0; + dfs(adj, visited, prev, postv, clock); + + for (int u = 0; u < adj.size(); u++) { + for (int v : adj.get(u)) { + if (postv[u] <= postv[v]) + return 1; + } + } + return 0; + } + + private static void dfs(ArrayList> adj, ArrayList visited, int[] prev, int[] postv, int[] clock) { + for (int v = 0; v < adj.size(); v++) { + if (!visited.contains(v)) + explore(adj, v, visited, prev, postv, clock); + } + } + + private static void explore(ArrayList> adj, int v, ArrayList visited, int[] prev, int[] postv, int[] clock) { + visited.add(v); + prev[v] = clock[0]; + clock[0] = clock[0] + 1; + + for (int n : adj.get(v)) { + if (!visited.contains(n)) + explore(adj, n, visited, prev, postv, clock); + } + postv[v] = clock[0]; + clock[0] = clock[0] + 1; + + } + + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + int n = scanner.nextInt(); + int m = scanner.nextInt(); + ArrayList> adj = new ArrayList>(); + for (int i = 0; i < n; i++) { + adj.add(new ArrayList()); + } + for (int i = 0; i < m; i++) { + int x, y; + x = scanner.nextInt(); + y = scanner.nextInt(); + adj.get(x - 1).add(y - 1); + } + System.out.println(acyclic(adj)); + } +} -- cgit v1.2.3