Question

C++ Write a program that outputs the nodes of a graph in a breadth-first traversal.

C++

Write a program that outputs the nodes of a graph in a breadth-first traversal.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

// Example program
#include <iostream>
#include <string>

#include <list>
#include <queue>
#include <cstdlib>
using namespace std;

struct AdjListNode{ //Adjacency List Node
int dest;
struct AdjListNode* next;
};

struct AdjList{ //Adjacency List
struct AdjListNode* head;
};

class Graph{
private:
int V;
struct AdjList* array;
public:
void BFS(int s);
Graph(int V){
this->V = V;
array = new AdjList [V];
for (int i = 0; i < V; ++i)
array[i].head = NULL;
}

AdjListNode* newAdjListNode(int dest){//create new adjacency list node
AdjListNode* newNode = new AdjListNode;
newNode->dest = dest;
newNode->next = NULL;
return newNode;
}

void addEdge(int src, int dest){ //Add Edge to Graph
AdjListNode* newNode = newAdjListNode(dest);
newNode->next = array[src].head;
array[src].head = newNode;
newNode = newAdjListNode(src);
newNode->next = array[dest].head;
array[dest].head = newNode;
}

void printGraph(){ //print grao
int v;
for (v = 0; v < V; ++v)
{
AdjListNode* pCrawl = array[v].head;
cout<<"\n Adjacency list of vertex "<<v<<"\n head ";
while (pCrawl)
{
cout<<"-> "<<pCrawl->dest;
pCrawl = pCrawl->next;
}
cout<<endl;
}
}
};

void Graph::BFS(int s)
{
bool *traversed = new bool[V];
for(int i = 0; i < V; i++)
traversed[i] = false;

list<int> q;

traversed[s] = true;
q.push_back(s);
list<int>::iterator i;

while(!q.empty())
{
s = q.front();
cout << s << " ";
q.pop_front();

for(AdjListNode* pCrawl = array[s].head; pCrawl!=NULL;)
{
if(!traversed[pCrawl->dest])
{
traversed[pCrawl->dest] = true;
q.push_back(pCrawl->dest);
  
}
pCrawl = pCrawl->next;
}
}
}

int main(){
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);
g.printGraph();
cout << "BFS from vertex 0"<<endl;
g.BFS(0);
  

  
}

=============================
See Output

D main.cpp DI main.cpp Adjacency list of vertex 0 head->2- 2- 1 /9 80 81 82 q.pop_front): for(Adj ListNode* pCrawl array [s].
Thanks, PLEASE UPVOTE if helpful

Add a comment
Know the answer?
Add Answer to:
C++ Write a program that outputs the nodes of a graph in a breadth-first traversal.
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT