Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- import java.util.concurrent.TimeUnit;
- public class Coba2{
- public static void main(String[] args){
- Scanner in = new Scanner(System.in);
- int nodes, bridges, start;
- nodes = in.nextInt();
- bridges = in.nextInt();
- start = in.nextInt();
- //Node array initialization
- int[] nodesArr = new int[nodes+1];
- initArray(nodesArr);
- //Matrix initialization
- LinkedList<LinkedList<Integer>> graph = new LinkedList<>();
- initList(graph, nodes);
- //Set the bridges in the matrix
- setList(graph, bridges);
- //Timer Start
- long startTime = System.nanoTime();
- //trace the graph
- System.out.println("Routes possible: ");
- trace(graph, nodesArr, start, "");
- //Timer End
- long endTime = System.nanoTime();
- //print Nodes where the graph is stuck
- printEnds(nodesArr);
- //Print Time elapsed
- long durationInMillis = TimeUnit.NANOSECONDS.toMillis(endTime - startTime);
- System.out.println("Time elapsed (in milliseconds): \n" + durationInMillis);
- in.close();
- }
- public static void initList(LinkedList<LinkedList<Integer>> graph, int nodes){
- for(int i = 0; i <= nodes; i++){
- graph.add(new LinkedList<Integer>());
- graph.get(i).add(i);
- }
- }
- public static void initArray(int[] arr){
- for(int i = 1; i < arr.length; i++){
- arr[i] = 0;
- }
- }
- public static void setList(LinkedList<LinkedList<Integer>> graph, int bridges){
- int u, v;
- Scanner in = new Scanner(System.in);
- for(int i = 0; i < bridges; i++){
- u = in.nextInt();
- v = in.nextInt();
- graph.get(u).add(v);
- }
- in.close();
- System.out.println();
- }
- public static void trace(LinkedList<LinkedList<Integer>> graph, int[] nodesArr, int start, String route){
- int nstart, prevstate;
- boolean advance = false;
- route = route + Integer.toString(start) + '-';
- if(nodesArr[start] == 0) nodesArr[start] = 1;
- if(nodesArr[start] == 2) nodesArr[start] = 3;
- //find all children of the node
- for(int i = 1; i < graph.get(start).size(); i++){
- //if a child is found, trace it deeper (DFS)
- nstart = graph.get(start).get(i);
- if(nodesArr[nstart] % 2 == 0){
- trace(graph, nodesArr, nstart, route);
- if (nodesArr[nstart] == 1) nodesArr[nstart] = 0;
- if (nodesArr[nstart] == 3) nodesArr[nstart] = 2;
- advance = true;
- }
- }
- //If already reached the end of route
- if (!advance) {
- System.out.println(route + "End of Route\n");
- nodesArr[start] = 2;
- }
- }
- public static void printEnds(int[] arr){
- System.out.println("Stucked in these islands: ");
- for(int i = 0; i < arr.length; i++){
- if(arr[i] >= 2){
- System.out.printf("%d ", i);
- }
- /* System.out.printf("%d ", arr[i]); */
- }
- System.out.println();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement