Advertisement
Guest User

Untitled

a guest
Nov 15th, 2019
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.62 KB | None | 0 0
  1. import java.util.*;
  2. public class vm7wc16_3 {
  3.     static class Graph{
  4.         private int V;
  5.         private LinkedList<Integer> houses[];
  6.  
  7.         Graph(int v){
  8.             this.V = v;
  9.             houses = new LinkedList[v];
  10.             for(int i=0; i<v; i++){
  11.                 houses[i] = new LinkedList();
  12.             }
  13.         }
  14.  
  15.         void addEdge(int x, int y){
  16.             houses[x].add(y);
  17.         }
  18.  
  19.         boolean BFS(int s, int e){
  20.             boolean [] visited = new boolean [V];
  21.             LinkedList<Integer> queue = new LinkedList<Integer>();
  22.             visited[s] = true;
  23.             queue.add(s);
  24.  
  25.             while(!queue.isEmpty()) {
  26.                 s = queue.poll();
  27.                 Iterator<Integer> i = houses[s].listIterator();
  28.                 while (i.hasNext()){
  29.                     int n = i.next();
  30.                     if(!visited[n]){
  31.                         if(n==e||s==e) return true;
  32.                         visited[n] = true;
  33.                         queue.add(n);
  34.                     }
  35.                 }
  36.             }
  37.             return false;
  38.         }
  39.     }
  40.     public static void main(String [] args){
  41.         Scanner sc = new Scanner(System.in);
  42.         int N = sc.nextInt();
  43.         int M = sc.nextInt();
  44.         int A = sc.nextInt()-1;
  45.         int B = sc.nextInt()-1;
  46.  
  47.         Graph g = new Graph(N);
  48.         for(int i=0; i<M; i++) {
  49.             g.addEdge(sc.nextInt()-1, sc.nextInt()-1 );
  50.         }
  51.         if(g.BFS(A,B)==true){
  52.             System.out.println("GO SHAHIR!");
  53.         } else{
  54.             System.out.println("NO SHAHIR!");
  55.         }
  56.  
  57.     }
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement