Graph traversal presentation of DSA
Graph traversal presentation of DSA
Graph traversal:-is the process of visiting all the nodes (vertices) in a graph in a
systematic way. It is essential for exploring graphs and solving various problems
like searching, pathfinding, and connectivity.
There are two main types of graph traversal:
Depth-First Search (DFS): Explores as far as possible along each branch before
backtracking. It uses a stack or recursion.
Breadth-First Search (BFS): Explores all neighbors at the current level before
moving to the next level. It uses a queue.
Breath First Search
Definition of BFS
Breadth-First Search (BFS)
is a graph traversal algorithm used to explore all the nodes (vertices) in a graph level by level.
It starts at a given node (source node), explores all neighboring nodes at the present depth
level before moving on to nodes at the next depth level.
Working Principle
BFS uses a queue data structure for storing nodes to be explored.
It follows the FIFO (First-In-First-Out) principle, ensuring nodes are processed level by
level.
Pseudo Code (BFS)
DFS(graph, start):
create stack S create set visited push start onto S while S is not empty:
node = pop from S if node is not in visited:
add node to visited for each neighbor of node:
push neighbor onto S
Application OF Depth-First
Search
1. Detecting cycle in a graph: A graph has a cycle if and
only if we see a back edge during DFS. So we can run
DFS for the graph and check for back edges.
2. Path Finding: We can specialize the DFS algorithm to
find a path between two given vertices u and z.
3. Web crawlers: Depth-first search can be used in the
implementation of web crawlers to explore the links
on a website.
4. Maze generation: Depth-first search can be used to
generate random mazes.
Application OF Depth-First
Search