Fetching the code, complexity notes and tags. Just a moment.
This snippet demonstrates how to perform a Breadth-First Search (BFS) traversal on a graph using a Queue. BFS explores all neighboring nodes level by level before moving to the next level, making it ideal for finding the shortest path in unweighted graphs, level-order traversal, and connectivity problems. It is one of the most frequently asked graph algorithms in coding interviews.
Category
graphs
Complexity
Time: O(V + E) | Space: O(V)
Language
Java
Status
Tags
Related Concepts
Published
Last Updated
Production-ready Java implementation for quick revision, interview preparation, and real-world development.
Solution.java
1import java.util.ArrayList;2import java.util.LinkedList;3import java.util.Queue;4 5public class GraphBFS {6 7 public static void bfs(ArrayList<ArrayList<Integer>> graph, int start) {8 9 boolean[] visited = new boolean[graph.size()];10 Queue<Integer> queue = new LinkedList<>();11 12 visited[start] = true;13 queue.offer(start);14 15 while (!queue.isEmpty()) {16 17 int node = queue.poll();18 19 System.out.print(node + " ");20 21 for (int neighbor : graph.get(node)) {22 23 if (!visited[neighbor]) {24 25 visited[neighbor] = true;26 queue.offer(neighbor);27 }28 }29 }30 }31 32 public static void main(String[] args) {33 34 int vertices = 6;35 36 ArrayList<ArrayList<Integer>> graph = new ArrayList<>();37 38 for (int i = 0; i < vertices; i++) {39 graph.add(new ArrayList<>());40 }41 42 graph.get(0).add(1);43 graph.get(0).add(2);44 45 graph.get(1).add(3);46 graph.get(1).add(4);47 48 graph.get(2).add(5);49 50 System.out.println("BFS Traversal:");51 52 bfs(graph, 0);53 }54}Keywords
Explore the important concepts and keywords associated with this Java snippet.
💡 These tags help you quickly identify the concepts covered in this snippet and make it easier to discover similar Java solutions throughout the library.