Skip to content

Instantly share code, notes, and snippets.

@manojnaidu619
Created July 9, 2019 10:51
Show Gist options
  • Save manojnaidu619/8d8d055f0492cdb7c7244d1df266c218 to your computer and use it in GitHub Desktop.
Save manojnaidu619/8d8d055f0492cdb7c7244d1df266c218 to your computer and use it in GitHub Desktop.
Breadth First Search(BFS) of a Graph in CPP
#include <iostream>
using namespace std;
// This is Implementation of Queue
struct Node {
int data;
struct Node *next;
}*front=NULL,*rear=NULL;
void enqueue(int ele){
struct Node *temp;
temp = new Node;
temp->data = ele;
temp->next = NULL;
if(front==NULL){
front=rear=temp;
}else{
rear->next = temp;
rear=temp;
}
}
int dequeue(){
if(front==NULL){
return 0;
}
struct Node *p=front;
int x;
x=front->data;
front = front->next;
delete p;
return x;
}
int isempty(){
return front==NULL;
}
// Queue implementation ends here
void BFS(int A[][7],int start, int n){
int visited[7]={0};
int i=start,j;
cout << i << " ";
visited[i] = 1;
enqueue(i);
while(!isempty()){
j = dequeue();
for(int x=1;x<n;x++){
if(A[j][x]==1 && visited[x]!=1){
cout << x << " ";
visited[x] = 1;
enqueue(x);
}
}
}
}
int main(){
int start=1;
int size=7;
int A[7][7]={{0,0,0,0,0,0,0},
{0,0,1,1,0,0,0},
{0,1,0,0,1,0,0},
{0,1,0,0,1,0,0},
{0,0,1,1,0,1,1},
{0,0,0,0,1,0,0},
{0,0,0,0,1,0,0}};
BFS(A,start,size);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment