SlideShare a Scribd company logo
Implement Breadth-First Search with a Queue
Solution
// Program to print BFS traversal from a given source vertex. BFS(int s)
// traverses vertices reachable from s.
#include
#include
using namespace std;
// This class represents a directed graph using adjacency list representation
class Graph
{
int V; // No. of vertices
list *adj; // Pointer to an array containing adjacency lists
public:
Graph(int V); // Constructor
void addEdge(int v, int w); // function to add an edge to graph
void BFS(int s); // prints BFS traversal from a given source s
};
Graph::Graph(int V)
{
this->V = V;
adj = new list[V];
}
void Graph::addEdge(int v, int w)
{
adj[v].push_back(w); // Add w to v’s list.
}
void Graph::BFS(int s)
{
// Mark all the vertices as not visited
bool *visited = new bool[V];
for(int i = 0; i < V; i++)
visited[i] = false;
// Create a queue for BFS
list queue;
// Mark the current node as visited and enqueue it
visited[s] = true;
queue.push_back(s);
// 'i' will be used to get all adjacent vertices of a vertex
list::iterator i;
while(!queue.empty())
{
// Dequeue a vertex from queue and print it
s = queue.front();
cout << s << " ";
queue.pop_front();
// Get all adjacent vertices of the dequeued vertex s
// If a adjacent has not been visited, then mark it visited
// and enqueue it
for(i = adj[s].begin(); i != adj[s].end(); ++i)
{
if(!visited[*i])
{
visited[*i] = true;
queue.push_back(*i);
}
}
}
}
// Driver program to test methods of graph class
int main()
{
// Create a graph given in the above diagram
Graph g(4);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);
cout << "Following is Breadth First Traversal "
<< "(starting from vertex 2)  ";
g.BFS(2);
return 0;
}
Output:
// Program to print BFS traversal from a given source vertex. BFS(int s)
// traverses vertices reachable from s.
#include
#include
using namespace std;
// This class represents a directed graph using adjacency list representation
class Graph
{
int V; // No. of vertices
list *adj; // Pointer to an array containing adjacency lists
public:
Graph(int V); // Constructor
void addEdge(int v, int w); // function to add an edge to graph
void BFS(int s); // prints BFS traversal from a given source s
};
Graph::Graph(int V)
{
this->V = V;
adj = new list[V];
}
void Graph::addEdge(int v, int w)
{
adj[v].push_back(w); // Add w to v’s list.
}
void Graph::BFS(int s)
{
// Mark all the vertices as not visited
bool *visited = new bool[V];
for(int i = 0; i < V; i++)
visited[i] = false;
// Create a queue for BFS
list queue;
// Mark the current node as visited and enqueue it
visited[s] = true;
queue.push_back(s);
// 'i' will be used to get all adjacent vertices of a vertex
list::iterator i;
while(!queue.empty())
{
// Dequeue a vertex from queue and print it
s = queue.front();
cout << s << " ";
queue.pop_front();
// Get all adjacent vertices of the dequeued vertex s
// If a adjacent has not been visited, then mark it visited
// and enqueue it
for(i = adj[s].begin(); i != adj[s].end(); ++i)
{
if(!visited[*i])
{
visited[*i] = true;
queue.push_back(*i);
}
}
}
}
// Driver program to test methods of graph class
int main()
{
// Create a graph given in the above diagram
Graph g(4);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);
cout << "Following is Breadth First Traversal "
<< "(starting from vertex 2)  ";
g.BFS(2);
return 0;
}

More Related Content

PDF
Im having trouble figuring out how to code these sections for an a.pdf
DOCX
Write a program that reads a graph from a file anil determines whethe.docx
PDF
Complete the implementation of the Weighted Graph that we began in t.pdf
PDF
ImplementDijkstra’s algorithm using the graph class you implemente.pdf
PDF
AI Lab print ptu universty st soldier collage .pdf
PDF
AI Lab menu for ptu students and easy to use and best quality and help for 6t...
PPS
C++ Language
PPT
13 Graph Classes
Im having trouble figuring out how to code these sections for an a.pdf
Write a program that reads a graph from a file anil determines whethe.docx
Complete the implementation of the Weighted Graph that we began in t.pdf
ImplementDijkstra’s algorithm using the graph class you implemente.pdf
AI Lab print ptu universty st soldier collage .pdf
AI Lab menu for ptu students and easy to use and best quality and help for 6t...
C++ Language
13 Graph Classes

More from mckenziecast21211 (20)

PDF
In a comparison of ectotherms and endotherms, which of the following.pdf
PDF
Immunology what are TdT and AID, and what are their roles in B c.pdf
PDF
IDS in the Cloud Please respond to the following(a) Explain w.pdf
PDF
Gandalf the Grey started in the Forest of Mirkwood at a point with co.pdf
PDF
Explain exploratory factor analysis and give real life examplesS.pdf
PDF
Drag the labels to the correct category to demonstrate your understan.pdf
PDF
Do you agree that the Berg Letter, research moratorium, and Asilomar.pdf
PDF
Brief Concepts and Questions EXAM 2 Chapter 8 DNA RNA Protein What i.pdf
PDF
A population has two alleles for a particular gene, A and a, and is .pdf
PDF
A 12-year-old male complained of strange odors before loss of consci.pdf
PDF
2.Which of the following statements about evolution is falseNonrand.pdf
PDF
can someone explain in a easy way chromosome walking I know its w.pdf
PDF
9. When a bacteriophage inserts its DNA into a bacterial chromosome,.pdf
PDF
Write an informal negation for each of the following statements. Be .pdf
PDF
Write a C++ program which generates and displays a random walk acros.pdf
PDF
true or false1- The grouped frequency table should ideally have.pdf
PDF
Answer the questions that follow the VHDL code given below. LIBRARY .pdf
PDF
The weak D phenotype is thought to arise from several mechanisms. .pdf
PDF
The coding region of a BACTERIAL gene has the following sequence A.pdf
PDF
Regarding the ABO blood group system in humans, if an individual is g.pdf
In a comparison of ectotherms and endotherms, which of the following.pdf
Immunology what are TdT and AID, and what are their roles in B c.pdf
IDS in the Cloud Please respond to the following(a) Explain w.pdf
Gandalf the Grey started in the Forest of Mirkwood at a point with co.pdf
Explain exploratory factor analysis and give real life examplesS.pdf
Drag the labels to the correct category to demonstrate your understan.pdf
Do you agree that the Berg Letter, research moratorium, and Asilomar.pdf
Brief Concepts and Questions EXAM 2 Chapter 8 DNA RNA Protein What i.pdf
A population has two alleles for a particular gene, A and a, and is .pdf
A 12-year-old male complained of strange odors before loss of consci.pdf
2.Which of the following statements about evolution is falseNonrand.pdf
can someone explain in a easy way chromosome walking I know its w.pdf
9. When a bacteriophage inserts its DNA into a bacterial chromosome,.pdf
Write an informal negation for each of the following statements. Be .pdf
Write a C++ program which generates and displays a random walk acros.pdf
true or false1- The grouped frequency table should ideally have.pdf
Answer the questions that follow the VHDL code given below. LIBRARY .pdf
The weak D phenotype is thought to arise from several mechanisms. .pdf
The coding region of a BACTERIAL gene has the following sequence A.pdf
Regarding the ABO blood group system in humans, if an individual is g.pdf
Ad

Recently uploaded (20)

PPTX
Microbial diseases, their pathogenesis and prophylaxis
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PDF
VCE English Exam - Section C Student Revision Booklet
PDF
Insiders guide to clinical Medicine.pdf
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PPTX
Institutional Correction lecture only . . .
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PDF
Anesthesia in Laparoscopic Surgery in India
PDF
Microbial disease of the cardiovascular and lymphatic systems
PPTX
GDM (1) (1).pptx small presentation for students
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PDF
TR - Agricultural Crops Production NC III.pdf
PPTX
Lesson notes of climatology university.
PDF
Computing-Curriculum for Schools in Ghana
PDF
Complications of Minimal Access Surgery at WLH
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
Microbial diseases, their pathogenesis and prophylaxis
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
VCE English Exam - Section C Student Revision Booklet
Insiders guide to clinical Medicine.pdf
Pharmacology of Heart Failure /Pharmacotherapy of CHF
Institutional Correction lecture only . . .
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
O5-L3 Freight Transport Ops (International) V1.pdf
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
Anesthesia in Laparoscopic Surgery in India
Microbial disease of the cardiovascular and lymphatic systems
GDM (1) (1).pptx small presentation for students
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
TR - Agricultural Crops Production NC III.pdf
Lesson notes of climatology university.
Computing-Curriculum for Schools in Ghana
Complications of Minimal Access Surgery at WLH
Module 4: Burden of Disease Tutorial Slides S2 2025
102 student loan defaulters named and shamed – Is someone you know on the list?
Ad

Implement Breadth-First Search with a QueueSolution Program .pdf

  • 1. Implement Breadth-First Search with a Queue Solution // Program to print BFS traversal from a given source vertex. BFS(int s) // traverses vertices reachable from s. #include #include using namespace std; // This class represents a directed graph using adjacency list representation class Graph { int V; // No. of vertices list *adj; // Pointer to an array containing adjacency lists public: Graph(int V); // Constructor void addEdge(int v, int w); // function to add an edge to graph void BFS(int s); // prints BFS traversal from a given source s }; Graph::Graph(int V) { this->V = V; adj = new list[V]; } void Graph::addEdge(int v, int w) { adj[v].push_back(w); // Add w to v’s list. } void Graph::BFS(int s) { // Mark all the vertices as not visited bool *visited = new bool[V]; for(int i = 0; i < V; i++) visited[i] = false; // Create a queue for BFS
  • 2. list queue; // Mark the current node as visited and enqueue it visited[s] = true; queue.push_back(s); // 'i' will be used to get all adjacent vertices of a vertex list::iterator i; while(!queue.empty()) { // Dequeue a vertex from queue and print it s = queue.front(); cout << s << " "; queue.pop_front(); // Get all adjacent vertices of the dequeued vertex s // If a adjacent has not been visited, then mark it visited // and enqueue it for(i = adj[s].begin(); i != adj[s].end(); ++i) { if(!visited[*i]) { visited[*i] = true; queue.push_back(*i); } } } } // Driver program to test methods of graph class int main() { // Create a graph given in the above diagram Graph g(4); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 2); g.addEdge(2, 0); g.addEdge(2, 3); g.addEdge(3, 3);
  • 3. cout << "Following is Breadth First Traversal " << "(starting from vertex 2) "; g.BFS(2); return 0; } Output: // Program to print BFS traversal from a given source vertex. BFS(int s) // traverses vertices reachable from s. #include #include using namespace std; // This class represents a directed graph using adjacency list representation class Graph { int V; // No. of vertices list *adj; // Pointer to an array containing adjacency lists public: Graph(int V); // Constructor void addEdge(int v, int w); // function to add an edge to graph void BFS(int s); // prints BFS traversal from a given source s }; Graph::Graph(int V) { this->V = V; adj = new list[V]; } void Graph::addEdge(int v, int w) { adj[v].push_back(w); // Add w to v’s list. } void Graph::BFS(int s) { // Mark all the vertices as not visited bool *visited = new bool[V];
  • 4. for(int i = 0; i < V; i++) visited[i] = false; // Create a queue for BFS list queue; // Mark the current node as visited and enqueue it visited[s] = true; queue.push_back(s); // 'i' will be used to get all adjacent vertices of a vertex list::iterator i; while(!queue.empty()) { // Dequeue a vertex from queue and print it s = queue.front(); cout << s << " "; queue.pop_front(); // Get all adjacent vertices of the dequeued vertex s // If a adjacent has not been visited, then mark it visited // and enqueue it for(i = adj[s].begin(); i != adj[s].end(); ++i) { if(!visited[*i]) { visited[*i] = true; queue.push_back(*i); } } } } // Driver program to test methods of graph class int main() { // Create a graph given in the above diagram Graph g(4); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 2);
  • 5. g.addEdge(2, 0); g.addEdge(2, 3); g.addEdge(3, 3); cout << "Following is Breadth First Traversal " << "(starting from vertex 2) "; g.BFS(2); return 0; }