Traversal
Traversal refers to the process of visiting all vertices(nodes) in a graph in a systematic way. There are primarily 2 ways for traversing graph, each with different applications and characteristics.
DFS
DFS explores by going down as deep as possible starting from a node and the backtracks to the next branch once it is done with the processing of the current branch. This algorithm makes use of either an explicit stack data structure (iteratively) or the call stack (recursive). Main applications fo DFS are
- Detecting cycles in a graph
- Topological sorting
- Finding strongly connected components
- Path finding in puzzles
How DFS works?
- Start at a choosen vertex
- Mark it as visited
- Explore an unvisited adjacent vertex
- Backtrack to the previous vertex and continue
BFS
BFS explores a graph level by level, visiting all vertices at the current depth before moving to vertices at the next depth level. It makes use of queue. Main applications of BFS are
- Finding shortest path in unweighted graphs
- Level-order Traversal
- Web Crawling
How BFS works?
- Start at a choosen vertex and add it to a queue
- While the queue is not empty:
- Remove a vertex from the front of the queue
- Mark it as visited
- Add all unvisited adjacent vertices to the back of the queue