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

linear search and binary search
linear search and binary searchlinear search and binary search
linear search and binary searchZia Ush Shamszaman
 
Topological Sorting
Topological SortingTopological Sorting
Topological SortingShahDhruv21
 
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 searchHossain Md Shakhawat
 
8 queens problem using back tracking
8 queens problem using back tracking8 queens problem using back tracking
8 queens problem using back trackingTech_MX
 
Depth first search [dfs]
Depth first search [dfs]Depth first search [dfs]
Depth first search [dfs]DEEPIKA T
 
Quick sort-Data Structure
Quick sort-Data StructureQuick sort-Data Structure
Quick sort-Data StructureJeanie Arnoco
 
BackTracking Algorithm: Technique and Examples
BackTracking Algorithm: Technique and ExamplesBackTracking Algorithm: Technique and Examples
BackTracking Algorithm: Technique and ExamplesFahim Ferdous
 
Introduction TO Finite Automata
Introduction TO Finite AutomataIntroduction TO Finite Automata
Introduction TO Finite AutomataRatnakar Mikkili
 
Graph traversal-BFS & DFS
Graph traversal-BFS & DFSGraph traversal-BFS & DFS
Graph traversal-BFS & DFSRajandeep Gill
 
Informed and Uninformed search Strategies
Informed and Uninformed search StrategiesInformed and Uninformed search Strategies
Informed and Uninformed search StrategiesAmey Kerkar
 

What's hot (20)

Heaps
HeapsHeaps
Heaps
 
Linked list
Linked listLinked list
Linked list
 
Tree in data structure
Tree in data structureTree in data structure
Tree in data structure
 
DFS and BFS
DFS and BFSDFS and BFS
DFS and BFS
 
linear search and binary search
linear search and binary searchlinear search and binary search
linear search and binary search
 
B and B+ tree
B and B+ treeB and B+ tree
B and B+ tree
 
Topological Sorting
Topological SortingTopological Sorting
Topological Sorting
 
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
 
A* Search Algorithm
A* Search AlgorithmA* Search Algorithm
A* Search Algorithm
 
8 queens problem using back tracking
8 queens problem using back tracking8 queens problem using back tracking
8 queens problem using back tracking
 
pushdown automata
pushdown automatapushdown automata
pushdown automata
 
Depth first search [dfs]
Depth first search [dfs]Depth first search [dfs]
Depth first search [dfs]
 
Quick sort-Data Structure
Quick sort-Data StructureQuick sort-Data Structure
Quick sort-Data Structure
 
BackTracking Algorithm: Technique and Examples
BackTracking Algorithm: Technique and ExamplesBackTracking Algorithm: Technique and Examples
BackTracking Algorithm: Technique and Examples
 
Infix to postfix conversion
Infix to postfix conversionInfix to postfix conversion
Infix to postfix conversion
 
Introduction TO Finite Automata
Introduction TO Finite AutomataIntroduction TO Finite Automata
Introduction TO Finite Automata
 
Spanning trees
Spanning treesSpanning trees
Spanning trees
 
Graph traversal-BFS & DFS
Graph traversal-BFS & DFSGraph traversal-BFS & DFS
Graph traversal-BFS & DFS
 
Graph coloring using backtracking
Graph coloring using backtrackingGraph coloring using backtracking
Graph coloring using backtracking
 
Informed and Uninformed search Strategies
Informed and Uninformed search StrategiesInformed and Uninformed search Strategies
Informed and Uninformed search Strategies
 

Similar to Breadth First Search & Depth First Search

Data Structure and Algorithms Graph Traversal
Data Structure and Algorithms Graph TraversalData Structure and Algorithms Graph Traversal
Data Structure and Algorithms Graph TraversalManishPrajapati78
 
Doubly & Circular Linked Lists
Doubly & Circular Linked ListsDoubly & Circular Linked Lists
Doubly & Circular Linked ListsAfaq Mansoor Khan
 
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.docxrandyburney60861
 
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 Ejeniihykdevara
 
Dsoop (co 221) 1
Dsoop (co 221) 1Dsoop (co 221) 1
Dsoop (co 221) 1Puja Koch
 
Lecture 03 lexical analysis
Lecture 03 lexical analysisLecture 03 lexical analysis
Lecture 03 lexical analysisIffat Anjum
 
lect- 3&4.ppt
lect- 3&4.pptlect- 3&4.ppt
lect- 3&4.pptmrizwan38
 
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_2019Bushra Al-Anesi
 
Stack and queue
Stack and queueStack and queue
Stack and queueLavanyaJ28
 
Nondeterministic Finite Automata AFN.pdf
Nondeterministic Finite Automata AFN.pdfNondeterministic Finite Automata AFN.pdf
Nondeterministic Finite Automata AFN.pdfSergioUlisesRojasAla
 
cs201-list-stack-queue.ppt
cs201-list-stack-queue.pptcs201-list-stack-queue.ppt
cs201-list-stack-queue.pptRahulYadav738822
 
Stacks IN DATA STRUCTURES
Stacks IN DATA STRUCTURESStacks IN DATA STRUCTURES
Stacks IN DATA STRUCTURESSowmya Jyothi
 
Unit II - LINEAR DATA STRUCTURES
Unit II -  LINEAR DATA STRUCTURESUnit II -  LINEAR DATA STRUCTURES
Unit II - LINEAR DATA STRUCTURESUsha Mahalingam
 
Unit 3 Stacks and Queues.pptx
Unit 3 Stacks and Queues.pptxUnit 3 Stacks and Queues.pptx
Unit 3 Stacks and Queues.pptxYogesh Pawar
 
Funddamentals of data structures
Funddamentals of data structuresFunddamentals of data structures
Funddamentals of data structuresGlobalidiots
 

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

EduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AIEduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AIkoyaldeepu123
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxk795866
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxbritheesh05
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfAsst.prof M.Gokilavani
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxKartikeyaDwivedi3
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineeringmalavadedarshan25
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVRajaP95
 
An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...Chandu841456
 
Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfROCENODodongVILLACER
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile servicerehmti665
 
Introduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHIntroduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHC Sai Kiran
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort servicejennyeacort
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AIabhishek36461
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSCAESB
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.eptoze12
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxDeepakSakkari2
 
Arduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptArduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptSAURABHKUMAR892774
 

Recently uploaded (20)

EduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AIEduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AI
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptx
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptx
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptx
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineering
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
 
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
 
An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...
 
Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdf
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile service
 
Introduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHIntroduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECH
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AI
 
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptxExploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentation
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptx
 
Design and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdfDesign and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdf
 
Arduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptArduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.ppt
 

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