Graph Traversals
Explore graph traversal methods such as breadth-first search and depth-first search in Java. Understand how these algorithms systematically visit nodes, their time and space complexities, and their practical applications in solving graph problems.
Graph traversal is the process of visiting all vertices (nodes) in a graph systematically. It is a fundamental concept because many graph algorithms rely on efficient graph exploration.
The two most common graph traversal techniques are:
Breadth-first search (BFS)
Depth-first search (DFS)
Breadth-first search (BFS)
Breadth-First Search explores a graph level by level. Starting from a chosen node, it first visits all immediate neighbors before moving to nodes at the next level.
Key idea
BFS uses a queue (FIFO: first in, first out).
How BFS works
Start from a chosen node.
Mark it as visited.
Add it to a queue.
While the queue is not empty:
Dequeue a node.
Visit all its unvisited neighbors.
Mark them as visited and add them to the queue.
Below is the Java implementation of BFS:
Time complexity:
The time complexity of BFS is