Last active
April 22, 2016 13:49
-
-
Save 78526Nasir/e2365e9c9e5d977f2bbe to your computer and use it in GitHub Desktop.
Breadth First Search Implementation in C !
This file contains 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
/// Breadth First Search Implementation in C /// | |
#include<stdlib.h> // this header file is needed for exit function | |
#include<stdio.h> | |
#define max 20 | |
int queue[max]; | |
int front,rear; | |
int BFS(int arr[][max],int ,int); | |
int dequeue(); | |
void enqueue(int); | |
int goal; | |
main() | |
{ | |
/// adjacent Matrix /// | |
int adjMatrix[][max]={ | |
{0,1,1,0,0,0,0,0}, | |
{1,0,1,0,0,0,0,0}, | |
{1,1,0,1,0,1,0,0}, | |
{0,0,1,0,1,0,1,0}, | |
{0,0,0,1,0,0,1,0}, | |
{0,0,1,0,0,0,0,1}, | |
{0,0,0,1,1,0,0,0}, | |
{0,0,0,0,0,1,0,0} | |
}; | |
int n=8; /// total number of Vertex | |
int root; | |
int flag=0; | |
printf("Breadth First Search\n"); | |
printf("--------------------\n"); | |
printf("Enter the Start Node :"); | |
scanf("%d",&root); | |
printf("Enter a goal:"); | |
scanf("%d",&goal); | |
flag=BFS(adjMatrix,n,root); | |
printf("\n"); | |
if(flag==1)printf("\nFound !\n"); | |
else | |
printf("\nNot Found !!!\n"); | |
} | |
int BFS(int arr[][max],int n,int root) | |
{ | |
int i,j; | |
int visited[n]; | |
for(i=0;i<n;i++) | |
visited[i]=0; | |
front=0; | |
rear=0; | |
enqueue(root); | |
printf("%d",root); | |
visited[root]=1; | |
while(front<=rear){ | |
i=dequeue(); | |
if(i==goal){ | |
return 1; | |
} | |
for(j=0;j<n;j++){ | |
if(visited[j]==0&&arr[i][j]==1){ | |
enqueue(j); | |
printf(" -> %d",j); | |
visited[j]=1; | |
if(j==goal){ | |
return 1; | |
} | |
} | |
} | |
} | |
printf("\n"); | |
return 0; | |
} | |
void enqueue(int ele) | |
{ | |
queue[rear]=ele; | |
rear++; | |
} | |
int dequeue(){ | |
int ele=queue[front]; | |
front++; | |
return ele; | |
} | |
/* | |
0--------1 3-----------4 | |
- | - - | | |
- | - - | | |
- | - - | | |
2---------5 -6 | |
- | |
- | |
7 | |
/// the above code is for this graph :) | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment