SlideShare a Scribd company logo
1 of 16
BFS – Breadth First Search
DFS – Depth First Search
Prepared by:
Kevin Jadiya
Subject : Data Structure
Topic:
 What is BFS ?????
•BFS stands for Breadth First Search.
•BFS is an algorithm for traversing or searching a tree or
graph data structures.
•It uses a queue data structure for implementation.
•In BFS traversal we visit all the nodes level by level and the
traversal completed when all the nodes are visited.
 Algorithm for BFS :
Step 1: Initialize all nodes with status=1.(ready state)
Step 2: Put starting node in a queue and change status to
status=2.(waiting state)
Step 3: loop:
repeat step 4 and step 5 until queue gets empty.
Step 4: Remove front node N from queue, process them and
change the status of N to status=3.(processed state)
Step 5: Add all the neighbours of N to the rear of queue and
change status to status=2.(waiting status)
A
B C
D E
F
A
B C
C D
D E
E F
A
A,B
A,B,C
A,B,C,D
A,B,C,D,E,F
F
F
F
F
F
R
R
R
R
 Working of BFC :
queue data structure
Queue gets empty and the algorithm ends
Code for BFC in C
#include<stdio.h>
#include<conio.h>
#define n 8
int A[8][8]={ {0,1,1,1,0,0,0,0},
{1,0,0,0,1,0,0,0},
{1,0,0,0,0,1,0,0},
{1,0,0,0,0,0,1,0},
{0,1,0,0,0,0,0,1},
{0,0,1,0,0,0,0,1},
{0,0,0,1,0,0,0,1},
{0,0,0,0,1,1,1,0}
};
int Front=-1;
int Rear=-1;
int Q[n];
int Visit[n];
void enqueue(int);
int dequeue();
void BFS();
void main()
{
int i,j,s;
clrscr();
printf("n Adjacency Matrix is : n");
for(i=0;i<=n-1;i++);
{
for(j=0;j<=n-1;j++)
{
printf(" %d",A[i][j]);
}
printf("n");
}
printf("Enter source code : ");
scanf("%d",&s);
printf("BFS traversal is : ");
BFS(s);
getch();
}
void BFS(int s)
{
int i,p;
enqueue(s);
Visit[s]=1;
loop:
p=dequeue();
if(p!=-1)
{
printf(" %d“,p);
for(i=0;i<=n-1;i++)
{
if(A[p][i]==1 && Visit[i]==0)
{
enqueue(i);
Visit[i]=1;
}
}
goto loop;
}
}
void enqueue(int s)
{
if(Rear==n-1)
printf("Queue is overflow");
else
{
Rear++;
Q[Rear]=s;
if(Front==-1)
{
Front=0;
}
}
}
int dequeue()
{
int item;
if(Front==-1)
{
return -1;
}
else
{
item=Q[Front];
if(Front==Rear)
{
Front=-1;
Rear=-1;
}
else
{
Front++;
}
return item;
}
}
What is DFS ?????
•DFS stands for Depth First Search.
•DFS is an algorithm for traversing or searching a
tree or graph data structures.
•It uses a stack data structure for implementation.
•In DFS one starts at the root and explores as far as
possible along each branch before backtracking.
Algorithm of DFS
[1]-- Initialize all nodes with status=1.(ready state)
[2]– Put starting node in the stack and change status
to status=2(waiting state).
[3]– Loop:-
Repeat step- 4 and step- 5 until stack Get empty.
[4]– Remove top node N from stack process them and
change the status of N processed state (status=3).
[5]– Add all the neighbours of N to the top of stack and
change status to waiting status-2.
 Working of DFC :
A
B C
D E
F
A
B
C
D
C
F
C
E
C C
output
A A
B
A
B
D
A
B
D
F
A
B
D
F
E
A
B
D
F
E
C
Stack data structure
#include<stdio.h>
#include<conio.h>
#define n 8
Int a[8][8]={
{0,1,1,1,0,0,0,0},
{1,0,0,0,1,0,0,0},
{1,0,0,0,0,1,0,0},
{1,0,0,0,0,0,1,0},
{0,1,0,0,0,0,0,1},
{0,0,1,0,0,0,0,1},
{0,0,0,1,0,0,0,1},
{0,0,0,0,1,1,1,0}
} ;
Int stack[20];
Int visit[8];
Int top=-1;
void dfs(int s);
void push(int item);
int pop();
void main()
{
int i,j,s;
clrscr();
printf("nn THE ADJACENCY
MATRIX IS nn");
for(i=0;i<=n-1;i++)
{
for(j=0;j<=n-1;j++)
{
printf(" %d ",a[i][j]);
}
printf("n");
}
printf("nn ENTER THE
SOURCE VERTEX : ");
Scanf("%d",&s);
printf("nn DFS
TRAVERSAL IS : ");
dfs(s);
getch();
}
Code for DFS in C :
void dfs(int s)
{
int i,k;
visit[s]=1;
k=pop();
if(k!=-1)
{
printf(" %d ",k);
visit[k]=1;
}
while(k!=-1)
{
for(i=n-1;i>=0;i--)
{
if(a[k][i]==1 &&
visit[i]==0)
{
push(i);
}
}
k=pop();
if(k!=-1)
{
if(visit[k]==0)
{
printf(" %d ",k);
visit[k]=1;
getch();
}
}
}
}
int pop()
{
int k;
if(top==-1)
{
return -1;
}
else
{
k=stack[top];
top = top - 1;
return k;
}
}
void push(int item)
{
if(top==9)
{
printf("Stack overflow ");
}
else
{ top = top + 1;
stack[top]=item;
}
}
DFS V/S BFS
• DFS stands for Depth
First Search.
• DFS can be done with
the help of STACK i.e.,
LIOF.
• In DFS has higher time
and space complexity,
because at a time it
needs to back tracing in
graph for traversal.
• BFS stands for Breadth
First Search.
• BFS can be done with
the help of QUEUE i.e.,
FIOF.
• In BFS the space & time
complexity is lesser as
there is no need to do
back tracing
DFS V/S BFS
• DFS is more faster then
BFS.
• DFS requires less
memory compare to
BFS.
• DFS is not so useful in
finding shortest path.
• Example :
A
/ 
B C
/ / 
D E F
Ans : A,B,D,C,E,F
• BFS is slower than DFS.
• BFS requires more
memory compare to
DFS.
• BFS is useful in finding
shortest path.
• Example :
A
/ 
B C
/ / 
D E F
Ans : A,B,C,D,E,F
Thank You

More Related Content

What's hot

What's hot (20)

Bubble sort
Bubble sortBubble sort
Bubble sort
 
Queue ppt
Queue pptQueue ppt
Queue ppt
 
Binary Search
Binary SearchBinary Search
Binary Search
 
Tree - Data Structure
Tree - Data StructureTree - Data Structure
Tree - Data Structure
 
Binary Tree Traversal
Binary Tree TraversalBinary Tree Traversal
Binary Tree Traversal
 
heap Sort Algorithm
heap  Sort Algorithmheap  Sort Algorithm
heap Sort Algorithm
 
Breadth first search and depth first search
Breadth first search and  depth first searchBreadth first search and  depth first search
Breadth first search and depth first search
 
DFS and BFS
DFS and BFSDFS and BFS
DFS and BFS
 
Binary search tree(bst)
Binary search tree(bst)Binary search tree(bst)
Binary search tree(bst)
 
Data structure ppt
Data structure pptData structure ppt
Data structure ppt
 
Introduction to data structure ppt
Introduction to data structure pptIntroduction to data structure ppt
Introduction to data structure ppt
 
DATA STRUCTURES
DATA STRUCTURESDATA STRUCTURES
DATA STRUCTURES
 
Binary Search Tree in Data Structure
Binary Search Tree in Data StructureBinary Search Tree in Data Structure
Binary Search Tree in Data Structure
 
Linked list
Linked listLinked list
Linked list
 
Heuristic Search Techniques Unit -II.ppt
Heuristic Search Techniques Unit -II.pptHeuristic Search Techniques Unit -II.ppt
Heuristic Search Techniques Unit -II.ppt
 
Array ppt
Array pptArray ppt
Array ppt
 
AVL Tree
AVL TreeAVL Tree
AVL Tree
 
Sparse matrix and its representation data structure
Sparse matrix and its representation data structureSparse matrix and its representation data structure
Sparse matrix and its representation data structure
 
linked list in data structure
linked list in data structure linked list in data structure
linked list in data structure
 
Data structure - Graph
Data structure - GraphData structure - Graph
Data structure - Graph
 

Similar to Breadth First Search & Depth First Search

Data Structures and Algorithm Analysis1. How much memory w.docx
Data Structures and Algorithm Analysis1. How much memory w.docxData Structures and Algorithm Analysis1. How much memory w.docx
Data Structures and Algorithm Analysis1. How much memory w.docx
randyburney60861
 
Data Structures and Algorithm AnalysisSpring 2020 Post Midterm E
Data Structures and Algorithm AnalysisSpring 2020 Post Midterm EData Structures and Algorithm AnalysisSpring 2020 Post Midterm E
Data Structures and Algorithm AnalysisSpring 2020 Post Midterm E
jeniihykdevara
 

Similar to Breadth First Search & Depth First Search (20)

Data Structure and Algorithms Graph Traversal
Data Structure and Algorithms Graph TraversalData Structure and Algorithms Graph Traversal
Data Structure and Algorithms Graph Traversal
 
Data structure
Data structureData structure
Data structure
 
Doubly & Circular Linked Lists
Doubly & Circular Linked ListsDoubly & Circular Linked Lists
Doubly & Circular Linked Lists
 
Data Structures and Algorithm Analysis1. How much memory w.docx
Data Structures and Algorithm Analysis1. How much memory w.docxData Structures and Algorithm Analysis1. How much memory w.docx
Data Structures and Algorithm Analysis1. How much memory w.docx
 
Data Structures and Algorithm AnalysisSpring 2020 Post Midterm E
Data Structures and Algorithm AnalysisSpring 2020 Post Midterm EData Structures and Algorithm AnalysisSpring 2020 Post Midterm E
Data Structures and Algorithm AnalysisSpring 2020 Post Midterm E
 
Dsoop (co 221) 1
Dsoop (co 221) 1Dsoop (co 221) 1
Dsoop (co 221) 1
 
Lecture 03 lexical analysis
Lecture 03 lexical analysisLecture 03 lexical analysis
Lecture 03 lexical analysis
 
lect- 3&4.ppt
lect- 3&4.pptlect- 3&4.ppt
lect- 3&4.ppt
 
Ch03 lexical analysis nfa_2_dfa_2019
Ch03 lexical analysis nfa_2_dfa_2019Ch03 lexical analysis nfa_2_dfa_2019
Ch03 lexical analysis nfa_2_dfa_2019
 
Algorithm
AlgorithmAlgorithm
Algorithm
 
linkedlist (1).ppt
linkedlist (1).pptlinkedlist (1).ppt
linkedlist (1).ppt
 
Stack and queue
Stack and queueStack and queue
Stack and queue
 
Nondeterministic Finite Automata AFN.pdf
Nondeterministic Finite Automata AFN.pdfNondeterministic Finite Automata AFN.pdf
Nondeterministic Finite Automata AFN.pdf
 
cs201-list-stack-queue.ppt
cs201-list-stack-queue.pptcs201-list-stack-queue.ppt
cs201-list-stack-queue.ppt
 
Singly linked list
Singly linked listSingly linked list
Singly linked list
 
Introduction To Stack
Introduction To StackIntroduction To Stack
Introduction To Stack
 
Stacks IN DATA STRUCTURES
Stacks IN DATA STRUCTURESStacks IN DATA STRUCTURES
Stacks IN DATA STRUCTURES
 
Unit II - LINEAR DATA STRUCTURES
Unit II -  LINEAR DATA STRUCTURESUnit II -  LINEAR DATA STRUCTURES
Unit II - LINEAR DATA STRUCTURES
 
Unit 3 Stacks and Queues.pptx
Unit 3 Stacks and Queues.pptxUnit 3 Stacks and Queues.pptx
Unit 3 Stacks and Queues.pptx
 
Funddamentals of data structures
Funddamentals of data structuresFunddamentals of data structures
Funddamentals of data structures
 

Recently uploaded

Verification of thevenin's theorem for BEEE Lab (1).pptx
Verification of thevenin's theorem for BEEE Lab (1).pptxVerification of thevenin's theorem for BEEE Lab (1).pptx
Verification of thevenin's theorem for BEEE Lab (1).pptx
chumtiyababu
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
ssuser89054b
 
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
AldoGarca30
 
Integrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - NeometrixIntegrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - Neometrix
Neometrix_Engineering_Pvt_Ltd
 
DeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakesDeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakes
MayuraD1
 

Recently uploaded (20)

Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torque
 
Employee leave management system project.
Employee leave management system project.Employee leave management system project.
Employee leave management system project.
 
Verification of thevenin's theorem for BEEE Lab (1).pptx
Verification of thevenin's theorem for BEEE Lab (1).pptxVerification of thevenin's theorem for BEEE Lab (1).pptx
Verification of thevenin's theorem for BEEE Lab (1).pptx
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
 
DC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equationDC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equation
 
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptxA CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
 
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
COST-EFFETIVE  and Energy Efficient BUILDINGS ptxCOST-EFFETIVE  and Energy Efficient BUILDINGS ptx
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
 
Introduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaIntroduction to Serverless with AWS Lambda
Introduction to Serverless with AWS Lambda
 
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
 
Engineering Drawing focus on projection of planes
Engineering Drawing focus on projection of planesEngineering Drawing focus on projection of planes
Engineering Drawing focus on projection of planes
 
kiln thermal load.pptx kiln tgermal load
kiln thermal load.pptx kiln tgermal loadkiln thermal load.pptx kiln tgermal load
kiln thermal load.pptx kiln tgermal load
 
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptx
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptxHOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptx
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptx
 
Integrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - NeometrixIntegrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - Neometrix
 
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKARHAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - V
 
DeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakesDeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakes
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . ppt
 
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced LoadsFEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
 
School management system project Report.pdf
School management system project Report.pdfSchool management system project Report.pdf
School management system project Report.pdf
 

Breadth First Search & Depth First Search

  • 1. BFS – Breadth First Search DFS – Depth First Search Prepared by: Kevin Jadiya Subject : Data Structure Topic:
  • 2.  What is BFS ????? •BFS stands for Breadth First Search. •BFS is an algorithm for traversing or searching a tree or graph data structures. •It uses a queue data structure for implementation. •In BFS traversal we visit all the nodes level by level and the traversal completed when all the nodes are visited.
  • 3.  Algorithm for BFS : Step 1: Initialize all nodes with status=1.(ready state) Step 2: Put starting node in a queue and change status to status=2.(waiting state) Step 3: loop: repeat step 4 and step 5 until queue gets empty. Step 4: Remove front node N from queue, process them and change the status of N to status=3.(processed state) Step 5: Add all the neighbours of N to the rear of queue and change status to status=2.(waiting status)
  • 4. A B C D E F A B C C D D E E F A A,B A,B,C A,B,C,D A,B,C,D,E,F F F F F F R R R R  Working of BFC : queue data structure Queue gets empty and the algorithm ends
  • 5. Code for BFC in C #include<stdio.h> #include<conio.h> #define n 8 int A[8][8]={ {0,1,1,1,0,0,0,0}, {1,0,0,0,1,0,0,0}, {1,0,0,0,0,1,0,0}, {1,0,0,0,0,0,1,0}, {0,1,0,0,0,0,0,1}, {0,0,1,0,0,0,0,1}, {0,0,0,1,0,0,0,1}, {0,0,0,0,1,1,1,0} }; int Front=-1; int Rear=-1; int Q[n]; int Visit[n]; void enqueue(int); int dequeue(); void BFS(); void main() { int i,j,s; clrscr(); printf("n Adjacency Matrix is : n"); for(i=0;i<=n-1;i++); { for(j=0;j<=n-1;j++) { printf(" %d",A[i][j]); } printf("n"); } printf("Enter source code : "); scanf("%d",&s); printf("BFS traversal is : "); BFS(s); getch(); }
  • 6. void BFS(int s) { int i,p; enqueue(s); Visit[s]=1; loop: p=dequeue(); if(p!=-1) { printf(" %d“,p); for(i=0;i<=n-1;i++) { if(A[p][i]==1 && Visit[i]==0) { enqueue(i); Visit[i]=1; } } goto loop; } } void enqueue(int s) { if(Rear==n-1) printf("Queue is overflow"); else { Rear++; Q[Rear]=s; if(Front==-1) { Front=0; } } }
  • 7. int dequeue() { int item; if(Front==-1) { return -1; } else { item=Q[Front]; if(Front==Rear) { Front=-1; Rear=-1; } else { Front++; } return item; } }
  • 8. What is DFS ????? •DFS stands for Depth First Search. •DFS is an algorithm for traversing or searching a tree or graph data structures. •It uses a stack data structure for implementation. •In DFS one starts at the root and explores as far as possible along each branch before backtracking.
  • 9. Algorithm of DFS [1]-- Initialize all nodes with status=1.(ready state) [2]– Put starting node in the stack and change status to status=2(waiting state). [3]– Loop:- Repeat step- 4 and step- 5 until stack Get empty. [4]– Remove top node N from stack process them and change the status of N processed state (status=3). [5]– Add all the neighbours of N to the top of stack and change status to waiting status-2.
  • 10.  Working of DFC : A B C D E F A B C D C F C E C C output A A B A B D A B D F A B D F E A B D F E C Stack data structure
  • 11. #include<stdio.h> #include<conio.h> #define n 8 Int a[8][8]={ {0,1,1,1,0,0,0,0}, {1,0,0,0,1,0,0,0}, {1,0,0,0,0,1,0,0}, {1,0,0,0,0,0,1,0}, {0,1,0,0,0,0,0,1}, {0,0,1,0,0,0,0,1}, {0,0,0,1,0,0,0,1}, {0,0,0,0,1,1,1,0} } ; Int stack[20]; Int visit[8]; Int top=-1; void dfs(int s); void push(int item); int pop(); void main() { int i,j,s; clrscr(); printf("nn THE ADJACENCY MATRIX IS nn"); for(i=0;i<=n-1;i++) { for(j=0;j<=n-1;j++) { printf(" %d ",a[i][j]); } printf("n"); } printf("nn ENTER THE SOURCE VERTEX : "); Scanf("%d",&s); printf("nn DFS TRAVERSAL IS : "); dfs(s); getch(); } Code for DFS in C :
  • 12. void dfs(int s) { int i,k; visit[s]=1; k=pop(); if(k!=-1) { printf(" %d ",k); visit[k]=1; } while(k!=-1) { for(i=n-1;i>=0;i--) { if(a[k][i]==1 && visit[i]==0) { push(i); } } k=pop(); if(k!=-1) { if(visit[k]==0) { printf(" %d ",k); visit[k]=1; getch(); } } } }
  • 13. int pop() { int k; if(top==-1) { return -1; } else { k=stack[top]; top = top - 1; return k; } } void push(int item) { if(top==9) { printf("Stack overflow "); } else { top = top + 1; stack[top]=item; } }
  • 14. DFS V/S BFS • DFS stands for Depth First Search. • DFS can be done with the help of STACK i.e., LIOF. • In DFS has higher time and space complexity, because at a time it needs to back tracing in graph for traversal. • BFS stands for Breadth First Search. • BFS can be done with the help of QUEUE i.e., FIOF. • In BFS the space & time complexity is lesser as there is no need to do back tracing
  • 15. DFS V/S BFS • DFS is more faster then BFS. • DFS requires less memory compare to BFS. • DFS is not so useful in finding shortest path. • Example : A / B C / / D E F Ans : A,B,D,C,E,F • BFS is slower than DFS. • BFS requires more memory compare to DFS. • BFS is useful in finding shortest path. • Example : A / B C / / D E F Ans : A,B,C,D,E,F