fork download
  1. import java.util.*;
  2. import java.lang.*;
  3. import java.io.*;
  4.  
  5. class Main
  6. {
  7. public static void main (String[] args) throws java.lang.Exception
  8. {
  9. Scanner sc = new Scanner(System.in);
  10.  
  11.  
  12. if (!sc.hasNextInt()) return;
  13.  
  14. int vertices = sc.nextInt();
  15. int edges = sc.nextInt();
  16.  
  17. // Initialize Adjacency List
  18. List<List<Integer>> adj = new ArrayList<>();
  19. for (int i = 0; i < vertices; i++) {
  20. adj.add(new ArrayList<>());
  21. }
  22.  
  23. // Read all graph edges from standard input
  24. for (int i = 0; i < edges; i++) {
  25. int u = sc.nextInt();
  26. int v = sc.nextInt();
  27.  
  28. // Build an undirected graph
  29. adj.get(u).add(v);
  30. adj.get(v).add(u);
  31. }
  32.  
  33.  
  34. int startNode = sc.nextInt();
  35.  
  36. System.out.print("BFS Traversal starting from node " + startNode + ": ");
  37. bfs(startNode, vertices, adj);
  38. }
  39.  
  40. public static void bfs(int startNode, int vertices, List<List<Integer>> adj) {
  41. Queue<Integer> queue = new LinkedList<>();
  42. boolean[] visited = new boolean[vertices];
  43.  
  44.  
  45. visited[startNode] = true;
  46. queue.add(startNode);
  47.  
  48. while (!queue.isEmpty()) {
  49. int curr = queue.poll();
  50. System.out.print(curr + " ");
  51.  
  52.  
  53. for (int neighbor : adj.get(curr)) {
  54. if (!visited[neighbor]) {
  55. visited[neighbor] = true;
  56. queue.add(neighbor);
  57. }
  58. }
  59. }
  60. System.out.println();
  61. }
  62. }
  63.  
Success #stdin #stdout 0.17s 60720KB
stdin
5 4
0 1
0 2
1 3
2 4
0
stdout
BFS Traversal starting from node 0: 0 1 2 3 4