Breadth-First Search

1. BFS in Graph

(1) Summary

  • Create adjacent list or adjacent matrix (prefer adjacent list since it is more space efficient) to build the graph mode given the relations

  • If each node can only be visited once, we should use an boolean array to check if the node has been visited

  • Pop a node from queue, and iterate over the node's neighbors and put them to the queue

(2) Template

class UndirectedGraphNode {
      int label;
      List<UndirectedGraphNode> neighbors;
      UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList<UndirectedGraphNode>(); }
};

public void BFSInGraph (UndirectedGraphNode node) {
     if (node == null) {
          return;
     }  

     Queue<UndirectedGraphNode> queue = new LinkedList<>();
     queue.add(node);

     while (!queue.isEmpty()) {
        UndirectedGraphNode curNode = queue.remove();

        for (UndirectedGraphNode nextNode : curNode.neighbors) {
            queue.add(nextNode);
        }
     }
}

2. BFS in Matrix

(1) Summary

  • Every cell in the matrix will be visited only once using BFS

  • Can calculate the distance to a given cell: Shortest Distance from All Buildings

  • If every cell can be visited only once, we can use either a boolean array to check if a cell has been visited or change the current value in the cell to avoid visiting it again: Surrounded Regions, (Here, we can flip the character 'O' to a special character '#' so that we won't visit the same cell again)

(2) Template

3. Time & Space Complexity

Time: O(V) , where V is the number of nodes in the graph

Space: O(V)

4. Questions Category

Last updated

Was this helpful?