Created
July 9, 2019 10:51
-
-
Save manojnaidu619/8d8d055f0492cdb7c7244d1df266c218 to your computer and use it in GitHub Desktop.
Breadth First Search(BFS) of a Graph in CPP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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