1. Home
  2. Coding Hub
  3. Coding Notes
  4. Java
  5. Graph Bfs
45% OFFBLACK FRIDAY SALE
Sale ends in
02Days
20Hrs
35Mins
03Secs
Claim
  1. Home
  2. Coding Hub
  3. Coding Notes
  4. Java
  5. Graph Bfs

Limited time offer

45% OFF

BLACK FRIDAY SALE

Sale ends in

02Days
20Hrs
35Mins
03Secs
Claim
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Underrated CoderUnderrated Coder
Underrated CoderUnderrated Coder
Resources
  • Coding Hub
  • Roadmap
  • DSA Sheet
  • Coding Notes
  • Coding Quiz
  • Code Compiler
  • Coder AI
Interview Preparation
  • 1:1 Mentorship
  • Interview Q&A
Community
  • Blog
  • Coder Community
Help & Support
  • Contact Us
  • Troubleshooting
  • Report a Bug
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Outline
JVM ArchitectureVariablesData TypesOperatorsIf-Else StatementsSwitch StatementsLoops (For, While)Methods (Functions)Variable Scope1D Arrays2D ArraysStringsStringBuilder
Classes & ObjectsConstructorsThe this KeywordInheritanceThe super KeywordPolymorphismMethod OverloadingMethod OverridingEncapsulationAccess ModifiersAbstract ClassesInterfaces
Try-CatchThrow vs. ThrowsCustom ExceptionsArrayListHashMapHashSetWrapper ClassesAutoboxing & Unboxing
Lambda ExpressionsStreams APIThe Optional Class
Singly Linked ListDoubly Linked ListStackQueuePriority QueueHash Map InternalsCircular Linked ListMonotonic StackCircular Queue
Linear SearchBinary SearchTwo Pointers PatternBig O Space ComplexityInsertion SortMerge SortQuick SortFixed Sliding WindowVariable Sliding WindowPrefix Sum Pattern
Binary TreesBSTPrefix TreesMin-HeapMax-HeapGraph Adjacency ListGraph Adjacency Matrix
Recursion FundamentalsBacktrackingBreadth-First SearchLevel OrderTree DFSInorder TraversalPreorder TraversalPostorder TraversalGraph DFSDijkstra's AlgorithmTopological Sort1D Dynamic Programming2D Dynamic ProgrammingTop-Down (Memoization)Bottom-Up (Tabulation)Cycle DetectionMerge Intervals Pattern
Java

Breadth-First Search

Overview

Breadth-First Search (BFS) is a fundamental algorithm for traversing Graphs and Trees. Instead of plunging deep down a single path, it explores the data structure level by level. Starting at a specific origin node, it visits all immediate neighbors first, then it visits all the neighbors' neighbors, and so on, radiating outward like a ripple in a pond.

The defining characteristic of BFS is its use of a Queue (First-In-First-Out data structure). This ensures that nodes discovered earlier (closer to the start) are processed before nodes discovered later.

Because of this strict radial expansion, BFS is the absolute gold standard for finding the Shortest Path in an unweighted graph (e.g., 'What is the minimum number of moves to escape a maze?'). If you need to find the closest item to your starting point, BFS guarantees that the first time you encounter the item, you have reached it via the shortest possible route.

Syntax

BFS using a Queue and Visited Set
java
import java.util.*;

public class GraphBFS {
    // Adjacency List graph representation
    Map<Integer, List<Integer>> adjList = new HashMap<>();

    public void bfs(int startNode) {
        // 1. The Queue tracks what to process next in FIFO order
        Queue<Integer> queue = new LinkedList<>();
        // 2. The Visited Set prevents infinite loops in cyclic graphs
        Set<Integer> visited = new HashSet<>();
        
        // Setup start node
        queue.offer(startNode);
        visited.add(startNode); // ALWAYS mark visited as soon as you enqueue!
        
        int distanceLevel = 0;
        
        while (!queue.isEmpty()) {
            int levelSize = queue.size(); // Lock in the size of the current level
            
            // Process ALL nodes on the current level before moving deeper
            for (int i = 0; i < levelSize; i++) {
                int curr = queue.poll();
                System.out.println("Processing Node " + curr + " at Distance " + distanceLevel);
                
                // Add all unvisited neighbors to the queue
                for (int neighbor : adjList.getOrDefault(curr, new ArrayList<>())) {
                    if (!visited.contains(neighbor)) {
                        visited.add(neighbor); // Mark visited immediately!
                        queue.offer(neighbor);
                    }
                }
            }
            distanceLevel++; // Moving one layer further away from the origin
        }
    }
}

Common Pitfalls

  • Marking nodes as visited when DEQUEUING instead of ENQUEUING. If you wait to mark a node visited until you poll() it out of the queue, multiple different nodes currently processing on the same level might see it as 'unvisited' and enqueue duplicates of the same node, causing massive memory bloat and TLE errors.
  • Forgetting the Visited Set entirely. In a Tree, a visited set isn't needed because data only flows downward. In a Graph, cycles exist. If Node A connects to Node B, and Node B connects back to Node A, BFS without a visited set will bounce between A and B infinitely.
  • Using a Stack instead of a Queue. If you accidentally instantiate a Stack instead of a LinkedList for your Queue interface, your algorithm instantly transforms into a Depth-First Search (DFS) and entirely loses its 'shortest path' level-by-level properties.

Interview Questions

Why does BFS guarantee the Shortest Path in an unweighted graph, whereas DFS does not?

BFS processes nodes strictly by distance from the origin. It processes all nodes at distance 1, then all nodes at distance 2, etc. Therefore, the very first time BFS encounters a target node, it is mathematically proven to be via the shortest possible path. DFS dives deep randomly and might find a path of length 100 before backtracking and finding a path of length 2.

What is the Time and Space Complexity of Graph BFS?

Time Complexity is O(V + E) where V is vertices and E is edges, because every node and every connected edge is processed at most once. Space Complexity is O(V) because in the worst-case (e.g., a star graph), the Queue and the Visited Set will need to store almost all V nodes simultaneously.

Real-World Example

Social Network 'Degrees of Separation'. When LinkedIn shows that someone is a '2nd connection' or '3rd connection', it runs a massive BFS starting from your profile. Level 1 (queue depth 1) contains your direct friends. Level 2 (queue depth 2) contains their friends. BFS instantly returns the shortest connection distance to any target user.

example
java
import java.util.*;

class User { String id; List<User> connections; }

public class LinkedInNetwork {
    public int findDegreesOfSeparation(User me, User target) {
        Queue<User> queue = new LinkedList<>();
        Set<User> visited = new HashSet<>();
        
        queue.offer(me); 
        visited.add(me);
        
        int degrees = 0;
        
        while(!queue.isEmpty()) {
            int size = queue.size();
            for(int i = 0; i < size; i++) {
                User curr = queue.poll();
                
                // We found the target user! Return the current depth level.
                if (curr.id.equals(target.id)) return degrees; 
                
                for(User connection : curr.connections) {
                    if(visited.add(connection)) { // Set.add() returns true if the item is newly added
                        queue.offer(connection);
                    }
                }
            }
            degrees++; // Increment degree of separation after processing the full level
        }
        return -1; // Users are completely unconnected in the graph
    }
}

Check Your Knowledge

Test your understanding of Breadth-First Search with these quick questions.

Question 1

What specific data structure is required to implement Breadth-First Search?

Question 2

When is the correct and safest time to mark a node as 'visited' in BFS?

Question 3

BFS is the standard algorithm for solving which specific class of problems?

Take Java Quiz
Outline
JVM ArchitectureVariablesData TypesOperatorsIf-Else StatementsSwitch StatementsLoops (For, While)Methods (Functions)Variable Scope1D Arrays2D ArraysStringsStringBuilder
Classes & ObjectsConstructorsThe this KeywordInheritanceThe super KeywordPolymorphismMethod OverloadingMethod OverridingEncapsulationAccess ModifiersAbstract ClassesInterfaces
Try-CatchThrow vs. ThrowsCustom ExceptionsArrayListHashMapHashSetWrapper ClassesAutoboxing & Unboxing
Lambda ExpressionsStreams APIThe Optional Class
Singly Linked ListDoubly Linked ListStackQueuePriority QueueHash Map InternalsCircular Linked ListMonotonic StackCircular Queue
Linear SearchBinary SearchTwo Pointers PatternBig O Space ComplexityInsertion SortMerge SortQuick SortFixed Sliding WindowVariable Sliding WindowPrefix Sum Pattern
Binary TreesBSTPrefix TreesMin-HeapMax-HeapGraph Adjacency ListGraph Adjacency Matrix
Recursion FundamentalsBacktrackingBreadth-First SearchLevel OrderTree DFSInorder TraversalPreorder TraversalPostorder TraversalGraph DFSDijkstra's AlgorithmTopological Sort1D Dynamic Programming2D Dynamic ProgrammingTop-Down (Memoization)Bottom-Up (Tabulation)Cycle DetectionMerge Intervals Pattern
Java

Breadth-First Search

Overview

Breadth-First Search (BFS) is a fundamental algorithm for traversing Graphs and Trees. Instead of plunging deep down a single path, it explores the data structure level by level. Starting at a specific origin node, it visits all immediate neighbors first, then it visits all the neighbors' neighbors, and so on, radiating outward like a ripple in a pond.

The defining characteristic of BFS is its use of a Queue (First-In-First-Out data structure). This ensures that nodes discovered earlier (closer to the start) are processed before nodes discovered later.

Because of this strict radial expansion, BFS is the absolute gold standard for finding the Shortest Path in an unweighted graph (e.g., 'What is the minimum number of moves to escape a maze?'). If you need to find the closest item to your starting point, BFS guarantees that the first time you encounter the item, you have reached it via the shortest possible route.

Syntax

BFS using a Queue and Visited Set
java
import java.util.*;

public class GraphBFS {
    // Adjacency List graph representation
    Map<Integer, List<Integer>> adjList = new HashMap<>();

    public void bfs(int startNode) {
        // 1. The Queue tracks what to process next in FIFO order
        Queue<Integer> queue = new LinkedList<>();
        // 2. The Visited Set prevents infinite loops in cyclic graphs
        Set<Integer> visited = new HashSet<>();
        
        // Setup start node
        queue.offer(startNode);
        visited.add(startNode); // ALWAYS mark visited as soon as you enqueue!
        
        int distanceLevel = 0;
        
        while (!queue.isEmpty()) {
            int levelSize = queue.size(); // Lock in the size of the current level
            
            // Process ALL nodes on the current level before moving deeper
            for (int i = 0; i < levelSize; i++) {
                int curr = queue.poll();
                System.out.println("Processing Node " + curr + " at Distance " + distanceLevel);
                
                // Add all unvisited neighbors to the queue
                for (int neighbor : adjList.getOrDefault(curr, new ArrayList<>())) {
                    if (!visited.contains(neighbor)) {
                        visited.add(neighbor); // Mark visited immediately!
                        queue.offer(neighbor);
                    }
                }
            }
            distanceLevel++; // Moving one layer further away from the origin
        }
    }
}

Common Pitfalls

  • Marking nodes as visited when DEQUEUING instead of ENQUEUING. If you wait to mark a node visited until you poll() it out of the queue, multiple different nodes currently processing on the same level might see it as 'unvisited' and enqueue duplicates of the same node, causing massive memory bloat and TLE errors.
  • Forgetting the Visited Set entirely. In a Tree, a visited set isn't needed because data only flows downward. In a Graph, cycles exist. If Node A connects to Node B, and Node B connects back to Node A, BFS without a visited set will bounce between A and B infinitely.
  • Using a Stack instead of a Queue. If you accidentally instantiate a Stack instead of a LinkedList for your Queue interface, your algorithm instantly transforms into a Depth-First Search (DFS) and entirely loses its 'shortest path' level-by-level properties.

Interview Questions

Why does BFS guarantee the Shortest Path in an unweighted graph, whereas DFS does not?

BFS processes nodes strictly by distance from the origin. It processes all nodes at distance 1, then all nodes at distance 2, etc. Therefore, the very first time BFS encounters a target node, it is mathematically proven to be via the shortest possible path. DFS dives deep randomly and might find a path of length 100 before backtracking and finding a path of length 2.

What is the Time and Space Complexity of Graph BFS?

Time Complexity is O(V + E) where V is vertices and E is edges, because every node and every connected edge is processed at most once. Space Complexity is O(V) because in the worst-case (e.g., a star graph), the Queue and the Visited Set will need to store almost all V nodes simultaneously.

Real-World Example

Social Network 'Degrees of Separation'. When LinkedIn shows that someone is a '2nd connection' or '3rd connection', it runs a massive BFS starting from your profile. Level 1 (queue depth 1) contains your direct friends. Level 2 (queue depth 2) contains their friends. BFS instantly returns the shortest connection distance to any target user.

example
java
import java.util.*;

class User { String id; List<User> connections; }

public class LinkedInNetwork {
    public int findDegreesOfSeparation(User me, User target) {
        Queue<User> queue = new LinkedList<>();
        Set<User> visited = new HashSet<>();
        
        queue.offer(me); 
        visited.add(me);
        
        int degrees = 0;
        
        while(!queue.isEmpty()) {
            int size = queue.size();
            for(int i = 0; i < size; i++) {
                User curr = queue.poll();
                
                // We found the target user! Return the current depth level.
                if (curr.id.equals(target.id)) return degrees; 
                
                for(User connection : curr.connections) {
                    if(visited.add(connection)) { // Set.add() returns true if the item is newly added
                        queue.offer(connection);
                    }
                }
            }
            degrees++; // Increment degree of separation after processing the full level
        }
        return -1; // Users are completely unconnected in the graph
    }
}

Check Your Knowledge

Test your understanding of Breadth-First Search with these quick questions.

Question 1

What specific data structure is required to implement Breadth-First Search?

Question 2

When is the correct and safest time to mark a node as 'visited' in BFS?

Question 3

BFS is the standard algorithm for solving which specific class of problems?

Take Java Quiz

Java coding notes for Indian students — 79 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in Java

  1. JVM Architecture
  2. Variables
  3. Data Types
  4. Operators
  5. If-Else Statements
  6. Switch Statements
  7. Loops (For, While)
  8. Methods (Functions)
  9. Variable Scope
  10. 1D Arrays
  11. 2D Arrays
  12. Strings
  13. StringBuilder
  14. Classes & Objects
  15. Constructors
  16. The this Keyword
  17. Inheritance
  18. The super Keyword
  19. Polymorphism
  20. Method Overloading
  21. Method Overriding
  22. Encapsulation
  23. Access Modifiers
  24. Abstract Classes
  25. Interfaces
  26. Try-Catch
  27. Throw vs. Throws
  28. Custom Exceptions
  29. ArrayList
  30. HashMap
  31. HashSet
  32. Wrapper Classes
  33. Autoboxing & Unboxing
  34. Lambda Expressions
  35. Streams API
  36. The Optional Class
  37. Singly Linked List
  38. Doubly Linked List
  39. Stack
  40. Queue
  41. Priority Queue
  42. Hash Map Internals
  43. Circular Linked List
  44. Monotonic Stack
  45. Circular Queue
  46. Linear Search
  47. Binary Search
  48. Two Pointers Pattern
  49. Big O Space Complexity
  50. Insertion Sort
  51. Merge Sort
  52. Quick Sort
  53. Fixed Sliding Window
  54. Variable Sliding Window
  55. Prefix Sum Pattern
  56. Binary Trees
  57. BST
  58. Prefix Trees
  59. Min-Heap
  60. Max-Heap
  61. Graph Adjacency List
  62. Graph Adjacency Matrix
  63. Recursion Fundamentals
  64. Backtracking
  65. Breadth-First Search
  66. Level Order
  67. Tree DFS
  68. Inorder Traversal
  69. Preorder Traversal
  70. Postorder Traversal
  71. Graph DFS
  72. Dijkstra's Algorithm
  73. Topological Sort
  74. 1D Dynamic Programming
  75. 2D Dynamic Programming
  76. Top-Down (Memoization)
  77. Bottom-Up (Tabulation)
  78. Cycle Detection
  79. Merge Intervals Pattern

Study next

  • All coding notes
  • Java notes home
  • Java certification quiz
  • Online compiler
  • Interview Q&A

Java coding notes for Indian students — 79 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in Java

  1. JVM Architecture
  2. Variables
  3. Data Types
  4. Operators
  5. If-Else Statements
  6. Switch Statements
  7. Loops (For, While)
  8. Methods (Functions)
  9. Variable Scope
  10. 1D Arrays
  11. 2D Arrays
  12. Strings
  13. StringBuilder
  14. Classes & Objects
  15. Constructors
  16. The this Keyword
  17. Inheritance
  18. The super Keyword
  19. Polymorphism
  20. Method Overloading
  21. Method Overriding
  22. Encapsulation
  23. Access Modifiers
  24. Abstract Classes
  25. Interfaces
  26. Try-Catch
  27. Throw vs. Throws
  28. Custom Exceptions
  29. ArrayList
  30. HashMap
  31. HashSet
  32. Wrapper Classes
  33. Autoboxing & Unboxing
  34. Lambda Expressions
  35. Streams API
  36. The Optional Class
  37. Singly Linked List
  38. Doubly Linked List
  39. Stack
  40. Queue
  41. Priority Queue
  42. Hash Map Internals
  43. Circular Linked List
  44. Monotonic Stack
  45. Circular Queue
  46. Linear Search
  47. Binary Search
  48. Two Pointers Pattern
  49. Big O Space Complexity
  50. Insertion Sort
  51. Merge Sort
  52. Quick Sort
  53. Fixed Sliding Window
  54. Variable Sliding Window
  55. Prefix Sum Pattern
  56. Binary Trees
  57. BST
  58. Prefix Trees
  59. Min-Heap
  60. Max-Heap
  61. Graph Adjacency List
  62. Graph Adjacency Matrix
  63. Recursion Fundamentals
  64. Backtracking
  65. Breadth-First Search
  66. Level Order
  67. Tree DFS
  68. Inorder Traversal
  69. Preorder Traversal
  70. Postorder Traversal
  71. Graph DFS
  72. Dijkstra's Algorithm
  73. Topological Sort
  74. 1D Dynamic Programming
  75. 2D Dynamic Programming
  76. Top-Down (Memoization)
  77. Bottom-Up (Tabulation)
  78. Cycle Detection
  79. Merge Intervals Pattern

Study next

  • All coding notes
  • Java notes home
  • Java certification quiz
  • Online compiler
  • Interview Q&A