Breadth-First Search (BFS)
Breadth First, it's source code and the questions to practice on.
Definition
Breadth First Search is an algorithm for traversing and searching Trees or Graphs. It usually starts at the root node moving on to the next-level nodes and analyzing layer by layer. It must traverse the nodes at the same level first before moving on to the next levels.
It traverses breadth-wise in the data-structure.
BFS utilizes queues instead of stack like in DFS.
It operates on FIFO (First-In-First-Out).
It marks all the visited nodes.
Figure credit to simplilearn
Implementation
Start at the root node.
Add the current node to the front of the queue.
Make a list of Nodes that are close to the vertex.
Dequeue nodes once they are visited.
Repeat the above steps till the queue is empty.
Questions to Practice on Leetcode
- Find a Corresponding Node of a Binary Tree in a Clone of That Tree
- Invert Binary Tree
- Same Tree
- Count Good Nodes in Binary Tree
- Binary Tree Level Order Traversal
- Add One Row to Tree
Source Code
import java.util.*;
// A class to store a graph edge
class Edge
{
int source, dest;
public Edge(int source, int dest)
{
this.source = source;
this.dest = dest;
}
}
// A class to represent a graph object
class Graph
{
// A list of lists to represent an adjacency list
List<List<Integer>> adjList = null;
// Constructor
Graph(List<Edge> edges, int n)
{
adjList = new ArrayList<>();
for (int i = 0; i < n; i++) {
adjList.add(new ArrayList<>());
}
// add edges to the undirected graph
for (Edge edge: edges)
{
int src = edge.source;
int dest = edge.dest;
adjList.get(src).add(dest);
adjList.get(dest).add(src);
}
}
}
class Main
{
// Perform BFS on the graph starting from vertex `v`
public static void BFS(Graph graph, int v, boolean[] discovered)
{
// create a queue for doing BFS
Queue<Integer> q = new ArrayDeque<>();
// mark the source vertex as discovered
discovered[v] = true;
// enqueue source vertex
q.add(v);
// loop till queue is empty
while (!q.isEmpty())
{
// dequeue front node and print it
v = q.poll();
System.out.print(v + " ");
// do for every edge (v, u)
for (int u: graph.adjList.get(v))
{
if (!discovered[u])
{
// mark it as discovered and enqueue it
discovered[u] = true;
q.add(u);
}
}
}
}
public static void main(String[] args)
{
// List of graph edges as per the above diagram
List<Edge> edges = Arrays.asList(
new Edge(1, 2), new Edge(1, 3), new Edge(1, 4), new Edge(2, 5),
new Edge(2, 6), new Edge(5, 9), new Edge(5, 10), new Edge(4, 7),
new Edge(4, 8), new Edge(7, 11), new Edge(7, 12)
// vertex 0, 13, and 14 are single nodes
);
// total number of nodes in the graph (labelled from 0 to 14)
int n = 15;
// build a graph from the given edges
Graph graph = new Graph(edges, n);
// to keep track of whether a vertex is discovered or not
boolean[] discovered = new boolean[n];
// Perform BFS traversal from all undiscovered nodes to
// cover all connected components of a graph
for (int i = 0; i < n; i++)
{
if (discovered[i] == false)
{
// start BFS traversal from vertex `i`
BFS(graph, i, discovered);
}
}
}
}