From bc5a6815181068e76316aa4a611647124d18ba48 Mon Sep 17 00:00:00 2001 From: Haidong Ji Date: Sun, 10 May 2020 16:18:46 -0500 Subject: Reachability done. I found it much easier to work with Java than Python. I tried to start with Python but found it difficult to get started. --- src/main/Reachability.java | 47 ++++++++++++++++++++++++++++++++++++++++++ src/test/ReachabilityTest.java | 38 ++++++++++++++++++++++++++++++++++ 2 files changed, 85 insertions(+) create mode 100644 src/main/Reachability.java create mode 100644 src/test/ReachabilityTest.java (limited to 'src') diff --git a/src/main/Reachability.java b/src/main/Reachability.java new file mode 100644 index 0000000..8d6ab78 --- /dev/null +++ b/src/main/Reachability.java @@ -0,0 +1,47 @@ +import java.util.ArrayList; +import java.util.Scanner; + +public class Reachability { + + static int reach(ArrayList> adj, int x, int y) { + ArrayList visited = new ArrayList<>(); + if (x == y) + return 1; + explore(adj, visited, x, y); + if (visited.contains(y)) + return 1; + return 0; + } + + private static void explore(ArrayList> adj, ArrayList visited, int x, int y) { + visited.add(x); + if (x == y) + return; + for (int n : adj.get(x)) { + if (!visited.contains(n)) + explore(adj, visited, n, y); + } + } + + + 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); + adj.get(y - 1).add(x - 1); + } + int x = scanner.nextInt() - 1; + int y = scanner.nextInt() - 1; + System.out.println(reach(adj, x, y)); + } +} + diff --git a/src/test/ReachabilityTest.java b/src/test/ReachabilityTest.java new file mode 100644 index 0000000..67b29b0 --- /dev/null +++ b/src/test/ReachabilityTest.java @@ -0,0 +1,38 @@ +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; + +import static org.junit.jupiter.api.Assertions.*; + +class ReachabilityTest { + + @Test + void test() { + ArrayList> adj = new ArrayList<>(); + for (int i = 0; i < 4; i++) { + adj.add(new ArrayList<>()); + } + + adj.get(0).add(1); + adj.get(2).add(1); + adj.get(3).add(2); + adj.get(0).add(3); + + assertEquals(1, Reachability.reach(adj, 0, 3)); + } + + @Test + void test1() { + ArrayList> adj = new ArrayList<>(); + for (int i = 0; i < 4; i++) { + adj.add(new ArrayList<>()); + } + + adj.get(0).add(1); + + adj.get(2).add(1); + + assertEquals(0, Reachability.reach(adj, 0, 3)); + } + +} \ No newline at end of file -- cgit v1.2.3