fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static void main (String[] args) throws java.lang.Exception
  11. {
  12. Scanner sc = new Scanner(System.in);
  13. int n = sc.nextInt();
  14. int m = sc.nextInt();
  15. List<List<Integer>> adj = new ArrayList<>();
  16. for(int i=0; i<=n;i++){
  17. adj.add(new ArrayList<>());
  18. }
  19.  
  20. for(int i=0; i<m; i++){
  21. int u = sc.nextInt();
  22. int v = sc.nextInt();
  23. adj.get(u).add(v);
  24. adj.get(v).add(u);
  25. }
  26. System.out.println(adj);
  27. isReachable(adj,6);
  28. }
  29.  
  30. public static void isReachable( List<List<Integer>> adj,int src){
  31. Queue<Integer> q = new LinkedList<>();
  32. boolean visited[] = new boolean[adj.size()];
  33. q.add(src);
  34. visited[src] = true;
  35.  
  36. while(!q.isEmpty()){
  37. int cur = q.poll();
  38.  
  39. for(int x : adj.get(cur)){
  40. if(!visited[x]){
  41. q.add(x);
  42. visited[x] = true;
  43. }
  44. }
  45. }
  46.  
  47. for(int i = 1; i< visited.length; i++){
  48. System.out.print(visited[i]+" ");
  49. }
  50. }
  51.  
  52. }
Success #stdin #stdout 0.16s 58916KB
stdin
7
5
1 2
1 3
2 5
3 4
6 7
stdout
[[], [2, 3], [1, 5], [1, 4], [3], [2], [7], [6]]
false false false false false true true