You are on page 1of 8

BFS & DFS

FROM : M . AHMAD
ROLL NO: BSCM-F20-035
What is BFS

The Breath First Search is an algorithm for traversing or searching tree or

graph data structures. It explores all the nodes at the present depth

before moving on to the nodes at the next depth level.


Steps for the BFS

 Pick a node and enqueue all its adjacent nodes into a queue.

 Dequeue a node from the queue, mark it as visited and enqueue all its
adjacent nodes into a queue.

 Repeat this process until the queue is empty or you meet a goal
Advantages and Disadvantages of BFS

Advantages:
 A BFS will find the shortest path between the starting point and any
other reachable node. A depth-first search will not necessarily find
the shortest path.

Disadvantages
 A BFS on a binary tree generally requires more memory than a DFS.
What is DFS

Depth-first search (DFS) is an algorithm for traversing or

searching tree or graph data structures. The algorithm starts at

the root node (selecting some arbitrary node as the root node in

the case of a graph) and explores as far as possible along each

branch before backtracking.


Steps for the DFS

 Step 1: PUSH the starting node into the stack.


 Step 2: If the stack is empty then stop and return failure.
 Step 3: If the top node of the stack is the goal node, then stop and return
success.
 Step 4: Else POP the top node from the stack and process it. Find all its
neighbors that are in ready state and PUSH them into the stack in any order.
 Step 5: Go to step 3.
 Step 6: Exit.
Advantages and Disadvantages of DFS

Advantages
 DFSconsumes very less memory space.
 It will reach at the goal node in a less time period than BFS if it traverses in a
right path.
 It may find a solution without examining much of search because we may get
the desired solution in the very first go.
Disadvantages
 It is possible that may states keep reoccurring. There is no guarantee of
finding the goal node.
THANK YOU

You might also like