BFS.java 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. // Function to find BFS of Graph from given source s
  2. import java.util.*;
  3. class BFS {
  4. // BFS from given source s
  5. static ArrayList<Integer> bfs(
  6. ArrayList<ArrayList<Integer>> adj) {
  7. int V = adj.size();
  8. int s = 0; // source node
  9. // create an array to store the traversal
  10. ArrayList<Integer> res = new ArrayList<>();
  11. // Create a queue for BFS
  12. Queue<Integer> q = new LinkedList<>();
  13. // Initially mark all the vertices as not visited
  14. boolean[] visited = new boolean[V];
  15. // Mark source node as visited and enqueue it
  16. visited[s] = true;
  17. q.add(s);
  18. // Iterate over the queue
  19. while (!q.isEmpty()) {
  20. // Dequeue a vertex from queue and store it
  21. int curr = q.poll();
  22. res.add(curr);
  23. // Get all adjacent vertices of the dequeued
  24. // vertex curr If an adjacent has not been
  25. // visited, mark it visited and enqueue it
  26. for (int x : adj.get(curr)) {
  27. if (!visited[x]) {
  28. visited[x] = true;
  29. q.add(x);
  30. }
  31. }
  32. }
  33. return res;
  34. }
  35. public static void main(String[] args) {
  36. // create the adjacency list
  37. // { {2, 3, 1}, {0}, {0, 4}, {0}, {2} }
  38. ArrayList<ArrayList<Integer>> adj = new ArrayList<>();
  39. adj.add(new ArrayList<>(Arrays.asList(1, 2)));
  40. adj.add(new ArrayList<>(Arrays.asList(0, 2, 3)));
  41. adj.add(new ArrayList<>(Arrays.asList(0, 4)));
  42. adj.add(new ArrayList<>(Arrays.asList(1,4)));
  43. adj.add(new ArrayList<>(Arrays.asList(2,3)));
  44. ArrayList<Integer> ans = bfs(adj);
  45. for (int i : ans) {
  46. System.out.print(i + " ");
  47. }
  48. }
  49. }