SlideShare a Scribd company logo
1 of 21
Group Member
1. ATTA UL MUSTAFA
2. ARMGAN ALI
3. ALI RAZA
4. MOHAMMAD ALI
5. ABDUL REHMAN
 (4425)
 (4424)
 (4427)
 (4420)
 (4403)
Breadth First Search
Breadth First Search
 Traversal means visiting all the nodes of a
graph. Breadth first traversal or Breadth first
Search is a recursive algorithm for searching all
the vertices of a graph or tree data structure. In
this article, you will learn with the help of
examples the BFS algorithm, the code of the
breadth first search algorithm with
implementation in C, programs.
Breadth First SearchAlgorithm
A standard BFS implementation puts each vertex of the
graph into one of two categories:
1. Visited
2. Not visited.
The purpose of the algorithm is to mark each vertex as
visited while avoiding cycles.
The algorithm works as follows:
1. Start by putting any one of the graph's vertices
at the back of a queue.
2. Take the front item of the queue and add it to
the visited list.
3. Create a list of that vertex's adjacent nodes.
Add the ones which aren't in the visited list to
the back of the queue.
4. Keep repeating steps 2 and 3 until the queue
is empty.
The graph might have two different disconnected
parts so to make sure that we cover every vertex,
we can also run the BFS algorithm on every
node.
BFS EXAMPLE
Let's see how the Breadth First Search
algorithm works with an example. We
use an undirected graph with 5 vertices.
We start from vertex 0, the BFS algorithm starts by
putting it in the Visited list and putting all its
adjacent vertices in the stack.
Next, we visit the element at the front of queue i.e. 1
and go to its adjacent nodes. Since 0 has already been
visited, we visit 2 instead
Vertex 2 has an unvisited adjacent vertex in 4,
so we add that to the back of the queue
and visit 3, which is at the front
of the queue.
Only 4 remains in the queue since the only adjacent
node of 3 i.e. 0 is already visited.
We visit it.
Since the queue is empty, we have completed
the Depth First Traversal of the graph.
BFS CODE IN C
The code for the Breadth First Search Algorithm
with an example is shown below.
The code has been simplified so that we can
focus on the algorithm rather than other details.
#include <stdio.h>
#include <stdlib.h>
#define SIZE 40
struct queue {
int items[SIZE];
int front;
int rear;
};
struct queue* createQueue();
void enqueue(struct queue* q, int);
int dequeue(struct queue* q);
void display(struct queue* q);
int isEmpty(struct queue* q);
void printQueue(struct queue* q);
struct node
{
int vertex;
struct node* next;
};
struct node* createNode(int);
struct Graph
{
int numVertices;
struct node** adjLists;
int* visited;
};
struct Graph* createGraph(int vertices);
void addEdge(struct Graph* graph, int src, int dest);
void printGraph(structGraph* graph);
void bfs(struct Graph* graph, int startVertex);
int main()
{
struct Graph* graph = createGraph(6);
addEdge(graph, 0, 1);
addEdge(graph, 0, 2);
addEdge(graph, 1, 2);
addEdge(graph, 1, 4);
addEdge(graph, 1, 3);
addEdge(graph, 2, 4);
addEdge(graph, 3, 4);
bfs(graph, 0);
return 0;
}
void bfs(struct Graph* graph, int startVertex) {
struct queue* q = createQueue();
graph->visited[startVertex] = 1;
enqueue(q, startVertex);
while(!isEmpty(q)){
printQueue(q);
int currentVertex = dequeue(q);
printf("Visited %dn", currentVertex);
struct node* temp = graph->adjLists[currentVertex];
while(temp) {
int adjVertex = temp->vertex;
if(graph->visited[adjVertex] == 0){
graph->visited[adjVertex] = 1;
enqueue(q, adjVertex);
}
temp = temp->next;
}
}
}
struct node* createNode(int v)
{
struct node* newNode = malloc(sizeof(struct node));
newNode->vertex = v;
newNode->next = NULL;
return newNode;
}
struct Graph* createGraph(int vertices)
{
struct Graph* graph = malloc(sizeof(structGraph));
graph->numVertices = vertices;
graph->adjLists = malloc(vertices * sizeof(struct node*));
graph->visited = malloc(vertices * sizeof(int));
int i;
for (i = 0; i < vertices; i++) {
graph->adjLists[i] = NULL;
graph->visited[i] = 0;
}
return graph;
}
void addEdge(struct Graph* graph, int src, int dest)
{
// Add edge from src to dest
struct node* newNode = createNode(dest);
newNode->next = graph->adjLists[src];
graph->adjLists[src] = newNode;
// Add edge from dest to src
newNode = createNode(src);
newNode->next = graph->adjLists[dest];
graph->adjLists[dest] = newNode;
}
struct queue* createQueue() {
struct queue* q = malloc(sizeof(struct queue));
q->front = -1;
q->rear = -1;
return q;
}
int isEmpty(struct queue* q) {
if(q->rear == -1)
return 1;
else
return 0;
}
void enqueue(struct queue* q, int value)
{
if(q->rear == SIZE-1)
printf("nQueue is Full!!");
else {
if(q->front == -1)
q->front = 0;
q->rear++;
q->items[q->rear] = value;
}
}
int dequeue(struct queue* q){
int item;
if(isEmpty(q)){
printf("Queue is empty");
item = -1;
}
else{
item = q->items[q->front];
q->front++;
if(q->front > q->rear){
printf("Resetting queue");
q->front = q->rear = -1;
}
}
return item;
}
void printQueue(struct queue *q) {
int i = q->front;
if(isEmpty(q)) {
printf("Queue is empty");
} else {
printf("nQueue contains n");
for(i = q->front; i < q->rear + 1; i++) {
printf("%d ", q->items[i]);
}
}
}
THANK YOU

More Related Content

What's hot (20)

stack presentation
stack presentationstack presentation
stack presentation
 
Introduction To Stack
Introduction To StackIntroduction To Stack
Introduction To Stack
 
Stack - Data Structure
Stack - Data StructureStack - Data Structure
Stack - Data Structure
 
Ch17
Ch17Ch17
Ch17
 
Stacks and Queue - Data Structures
Stacks and Queue - Data StructuresStacks and Queue - Data Structures
Stacks and Queue - Data Structures
 
2Bytesprog2 course_2014_c7_double_lists
2Bytesprog2 course_2014_c7_double_lists2Bytesprog2 course_2014_c7_double_lists
2Bytesprog2 course_2014_c7_double_lists
 
Merge sort
Merge sortMerge sort
Merge sort
 
Lecture 3.2 bt
Lecture 3.2 btLecture 3.2 bt
Lecture 3.2 bt
 
New microsoft office word document (2)
New microsoft office word document (2)New microsoft office word document (2)
New microsoft office word document (2)
 
Doc 20180130-wa0006
Doc 20180130-wa0006Doc 20180130-wa0006
Doc 20180130-wa0006
 
Ch9c
Ch9cCh9c
Ch9c
 
Merge sort code in C explained
Merge sort code in C explained Merge sort code in C explained
Merge sort code in C explained
 
Stack & queue
Stack & queueStack & queue
Stack & queue
 
The Stack And Recursion
The Stack And RecursionThe Stack And Recursion
The Stack And Recursion
 
Stack data structure
Stack data structureStack data structure
Stack data structure
 
Infix prefix postfix
Infix prefix postfixInfix prefix postfix
Infix prefix postfix
 
Stack Data Structure
Stack Data StructureStack Data Structure
Stack Data Structure
 
Derivative3
Derivative3Derivative3
Derivative3
 
stacks and queues
stacks and queuesstacks and queues
stacks and queues
 
Queues-handouts
Queues-handoutsQueues-handouts
Queues-handouts
 

Similar to Group Members BFS

DS Unit 1.pptx
DS Unit 1.pptxDS Unit 1.pptx
DS Unit 1.pptxchin463670
 
bfs tree searching ,sortingUntitled presentation.pptx
bfs tree searching ,sortingUntitled presentation.pptxbfs tree searching ,sortingUntitled presentation.pptx
bfs tree searching ,sortingUntitled presentation.pptxsaurabhpandey679381
 
Standard Template Library (STL) in Object Oriented Programming
Standard Template Library (STL) in Object Oriented ProgrammingStandard Template Library (STL) in Object Oriented Programming
Standard Template Library (STL) in Object Oriented ProgrammingMandeep Singh
 
Array 31.8.2020 updated
Array 31.8.2020 updatedArray 31.8.2020 updated
Array 31.8.2020 updatedvrgokila
 
Java Algorithm Interview Questions & Answers .pdf
Java Algorithm Interview Questions & Answers .pdfJava Algorithm Interview Questions & Answers .pdf
Java Algorithm Interview Questions & Answers .pdfNiravPanchal50
 
Queue data structure
Queue data structureQueue data structure
Queue data structureMekk Mhmd
 
Data structures lab manual
Data structures lab manualData structures lab manual
Data structures lab manualSyed Mustafa
 
Revisiting a data structures in detail with linked list stack and queue
Revisiting a data structures in detail with linked list stack and queueRevisiting a data structures in detail with linked list stack and queue
Revisiting a data structures in detail with linked list stack and queuessuser7319f8
 
03 stacks and_queues_using_arrays
03 stacks and_queues_using_arrays03 stacks and_queues_using_arrays
03 stacks and_queues_using_arraystameemyousaf
 
Mouse programming in c
Mouse programming in cMouse programming in c
Mouse programming in cgkgaur1987
 
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbbqueuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbbRAtna29
 
Ds lab manual by s.k.rath
Ds lab manual by s.k.rathDs lab manual by s.k.rath
Ds lab manual by s.k.rathSANTOSH RATH
 
lect- 3&4.ppt
lect- 3&4.pptlect- 3&4.ppt
lect- 3&4.pptmrizwan38
 
Queue(lecture8).pptx
Queue(lecture8).pptxQueue(lecture8).pptx
Queue(lecture8).pptxsinghprpg
 

Similar to Group Members BFS (20)

05 queues
05 queues05 queues
05 queues
 
DS Unit 1.pptx
DS Unit 1.pptxDS Unit 1.pptx
DS Unit 1.pptx
 
bfs tree searching ,sortingUntitled presentation.pptx
bfs tree searching ,sortingUntitled presentation.pptxbfs tree searching ,sortingUntitled presentation.pptx
bfs tree searching ,sortingUntitled presentation.pptx
 
Standard Template Library (STL) in Object Oriented Programming
Standard Template Library (STL) in Object Oriented ProgrammingStandard Template Library (STL) in Object Oriented Programming
Standard Template Library (STL) in Object Oriented Programming
 
Array 31.8.2020 updated
Array 31.8.2020 updatedArray 31.8.2020 updated
Array 31.8.2020 updated
 
Java Algorithm Interview Questions & Answers .pdf
Java Algorithm Interview Questions & Answers .pdfJava Algorithm Interview Questions & Answers .pdf
Java Algorithm Interview Questions & Answers .pdf
 
Queues
Queues Queues
Queues
 
Queue data structure
Queue data structureQueue data structure
Queue data structure
 
Data structure
Data  structureData  structure
Data structure
 
Data structures lab manual
Data structures lab manualData structures lab manual
Data structures lab manual
 
Revisiting a data structures in detail with linked list stack and queue
Revisiting a data structures in detail with linked list stack and queueRevisiting a data structures in detail with linked list stack and queue
Revisiting a data structures in detail with linked list stack and queue
 
Stack and Queue
Stack and Queue Stack and Queue
Stack and Queue
 
Unit 2 dsa LINEAR DATA STRUCTURE
Unit 2 dsa LINEAR DATA STRUCTUREUnit 2 dsa LINEAR DATA STRUCTURE
Unit 2 dsa LINEAR DATA STRUCTURE
 
03 stacks and_queues_using_arrays
03 stacks and_queues_using_arrays03 stacks and_queues_using_arrays
03 stacks and_queues_using_arrays
 
STACK1.pptx
STACK1.pptxSTACK1.pptx
STACK1.pptx
 
Mouse programming in c
Mouse programming in cMouse programming in c
Mouse programming in c
 
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbbqueuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
 
Ds lab manual by s.k.rath
Ds lab manual by s.k.rathDs lab manual by s.k.rath
Ds lab manual by s.k.rath
 
lect- 3&4.ppt
lect- 3&4.pptlect- 3&4.ppt
lect- 3&4.ppt
 
Queue(lecture8).pptx
Queue(lecture8).pptxQueue(lecture8).pptx
Queue(lecture8).pptx
 

Recently uploaded

Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...M56BOOKSTORE PRODUCT/SERVICE
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaVirag Sontakke
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxsocialsciencegdgrohi
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxAvyJaneVismanos
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxJiesonDelaCerna
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...jaredbarbolino94
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,Virag Sontakke
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfadityarao40181
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 

Recently uploaded (20)

Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of India
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptx
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptx
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdf
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 

Group Members BFS

  • 1. Group Member 1. ATTA UL MUSTAFA 2. ARMGAN ALI 3. ALI RAZA 4. MOHAMMAD ALI 5. ABDUL REHMAN  (4425)  (4424)  (4427)  (4420)  (4403)
  • 3. Breadth First Search  Traversal means visiting all the nodes of a graph. Breadth first traversal or Breadth first Search is a recursive algorithm for searching all the vertices of a graph or tree data structure. In this article, you will learn with the help of examples the BFS algorithm, the code of the breadth first search algorithm with implementation in C, programs.
  • 4. Breadth First SearchAlgorithm A standard BFS implementation puts each vertex of the graph into one of two categories: 1. Visited 2. Not visited. The purpose of the algorithm is to mark each vertex as visited while avoiding cycles.
  • 5. The algorithm works as follows: 1. Start by putting any one of the graph's vertices at the back of a queue. 2. Take the front item of the queue and add it to the visited list. 3. Create a list of that vertex's adjacent nodes. Add the ones which aren't in the visited list to the back of the queue.
  • 6. 4. Keep repeating steps 2 and 3 until the queue is empty. The graph might have two different disconnected parts so to make sure that we cover every vertex, we can also run the BFS algorithm on every node.
  • 7. BFS EXAMPLE Let's see how the Breadth First Search algorithm works with an example. We use an undirected graph with 5 vertices.
  • 8. We start from vertex 0, the BFS algorithm starts by putting it in the Visited list and putting all its adjacent vertices in the stack.
  • 9. Next, we visit the element at the front of queue i.e. 1 and go to its adjacent nodes. Since 0 has already been visited, we visit 2 instead
  • 10. Vertex 2 has an unvisited adjacent vertex in 4, so we add that to the back of the queue and visit 3, which is at the front of the queue.
  • 11. Only 4 remains in the queue since the only adjacent node of 3 i.e. 0 is already visited. We visit it.
  • 12. Since the queue is empty, we have completed the Depth First Traversal of the graph.
  • 13. BFS CODE IN C The code for the Breadth First Search Algorithm with an example is shown below. The code has been simplified so that we can focus on the algorithm rather than other details.
  • 14. #include <stdio.h> #include <stdlib.h> #define SIZE 40 struct queue { int items[SIZE]; int front; int rear; }; struct queue* createQueue(); void enqueue(struct queue* q, int); int dequeue(struct queue* q); void display(struct queue* q); int isEmpty(struct queue* q); void printQueue(struct queue* q); struct node { int vertex; struct node* next; }; struct node* createNode(int); struct Graph
  • 15. { int numVertices; struct node** adjLists; int* visited; }; struct Graph* createGraph(int vertices); void addEdge(struct Graph* graph, int src, int dest); void printGraph(structGraph* graph); void bfs(struct Graph* graph, int startVertex); int main() { struct Graph* graph = createGraph(6); addEdge(graph, 0, 1); addEdge(graph, 0, 2); addEdge(graph, 1, 2); addEdge(graph, 1, 4); addEdge(graph, 1, 3); addEdge(graph, 2, 4); addEdge(graph, 3, 4); bfs(graph, 0); return 0; }
  • 16. void bfs(struct Graph* graph, int startVertex) { struct queue* q = createQueue(); graph->visited[startVertex] = 1; enqueue(q, startVertex); while(!isEmpty(q)){ printQueue(q); int currentVertex = dequeue(q); printf("Visited %dn", currentVertex); struct node* temp = graph->adjLists[currentVertex]; while(temp) { int adjVertex = temp->vertex; if(graph->visited[adjVertex] == 0){ graph->visited[adjVertex] = 1; enqueue(q, adjVertex); } temp = temp->next; } } }
  • 17. struct node* createNode(int v) { struct node* newNode = malloc(sizeof(struct node)); newNode->vertex = v; newNode->next = NULL; return newNode; } struct Graph* createGraph(int vertices) { struct Graph* graph = malloc(sizeof(structGraph)); graph->numVertices = vertices; graph->adjLists = malloc(vertices * sizeof(struct node*)); graph->visited = malloc(vertices * sizeof(int)); int i; for (i = 0; i < vertices; i++) { graph->adjLists[i] = NULL; graph->visited[i] = 0; }
  • 18. return graph; } void addEdge(struct Graph* graph, int src, int dest) { // Add edge from src to dest struct node* newNode = createNode(dest); newNode->next = graph->adjLists[src]; graph->adjLists[src] = newNode; // Add edge from dest to src newNode = createNode(src); newNode->next = graph->adjLists[dest]; graph->adjLists[dest] = newNode; } struct queue* createQueue() { struct queue* q = malloc(sizeof(struct queue)); q->front = -1; q->rear = -1; return q; }
  • 19. int isEmpty(struct queue* q) { if(q->rear == -1) return 1; else return 0; } void enqueue(struct queue* q, int value) { if(q->rear == SIZE-1) printf("nQueue is Full!!"); else { if(q->front == -1) q->front = 0; q->rear++; q->items[q->rear] = value; } } int dequeue(struct queue* q){ int item; if(isEmpty(q)){ printf("Queue is empty"); item = -1; }
  • 20. else{ item = q->items[q->front]; q->front++; if(q->front > q->rear){ printf("Resetting queue"); q->front = q->rear = -1; } } return item; } void printQueue(struct queue *q) { int i = q->front; if(isEmpty(q)) { printf("Queue is empty"); } else { printf("nQueue contains n"); for(i = q->front; i < q->rear + 1; i++) { printf("%d ", q->items[i]); } } }