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. // your code goes here
  13. Scanner sc=new Scanner(System.in);
  14. int n=sc.nextInt();
  15. int m=sc.nextInt();
  16.  
  17. ArrayList<ArrayList<Integer>> adj=new ArrayList<>();
  18. for(int i=0;i<=n;i++){
  19. adj.add(new ArrayList<>());
  20. }
  21. for(int i=1;i<=m;i++){
  22. int x=sc.nextInt();
  23. int y=sc.nextInt();
  24. adj.get(x).add(y);
  25. adj.get(y).add(x);
  26.  
  27. }
  28. Queue<Integer> q=new LinkedList<>();
  29. int src=1;
  30. boolean vis[]=new boolean[n+1];
  31. q.add(src);
  32. vis[src]=true;
  33. while(!q.isEmpty()){
  34. int node=q.poll();
  35. System.out.print(node+" ");
  36. for(int x: adj.get(node)){
  37. if(!vis[x]){
  38. vis[x]=true;
  39. q.add(x);
  40. }
  41. }
  42. }
  43.  
  44.  
  45.  
  46. }
  47. }
Success #stdin #stdout 0.14s 20060KB
stdin
5
5
1
2
3
4
2
3
4
5
3
5
stdout
1 2 3 4 5