summaryrefslogtreecommitdiff
path: root/src/main/Reachability.java
blob: 8d6ab784c0b6fa2acc068a7ebbdf5b71f507b405 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import java.util.ArrayList;
import java.util.Scanner;

public class Reachability {

    static int reach(ArrayList<ArrayList<Integer>> adj, int x, int y) {
        ArrayList<Integer> 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<ArrayList<Integer>> adj, ArrayList<Integer> 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<ArrayList<Integer>> adj = new ArrayList<ArrayList<Integer>>();
        for (int i = 0; i < n; i++) {
            adj.add(new ArrayList<Integer>());
        }
        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));
    }
}