Skip to content

Instantly share code, notes, and snippets.

@muhammedeminoglu
Last active May 25, 2020 16:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save muhammedeminoglu/0ccc518c955999250492a6e9482d59da to your computer and use it in GitHub Desktop.
Save muhammedeminoglu/0ccc518c955999250492a6e9482d59da to your computer and use it in GitHub Desktop.
BFS Algorithm C Code with Queue implementation. You have to have "matris.txt" file for nodes. Don't miss it.
#include <stdio.h>
#include <stdbool.h>
int graph[6][6];
bool visited[5];
struct node{
int data;
struct node *next;
};
struct node* first = NULL;
struct node* last = NULL;
struct node* createNode(int x)
{
struct node* newNode = (struct node*)malloc(sizeof(struct node));
newNode->data = x;
newNode->next = NULL;
return newNode;
}
void enQueue(int x)
{
struct node* newyNode = createNode(x);
if(first == NULL)
{
first = newyNode;
last = newyNode;
}
else
{
last->next = newyNode;
last = newyNode;
}
}
void deQueue()
{
if(first == NULL)
{
printf("\n Your Queue is already empty please enqueue an item");
return;
}
if(first->next == NULL)
{
first = NULL;
last = NULL;
}
else
{
struct node* secondNode = first->next;
free(first);
first = secondNode;
}
}
bool isEmpty()
{
if(first == NULL)
return true;
else
return false;
}
int next()
{
return first->data;
}
void BFS(int root)
{
int i;
for(i = 0; i < 6; i++)
{
visited[i] = false;
}
visited[root] = true;
enQueue(root);
while(isEmpty() == false)
{
root = next();
printf("%d ", root);
deQueue();
for( i = 0; i < 6; i++)
{
if(visited[i] == false && graph[root][i] == 1)
{
visited[i] = true;
enQueue(i);
}
}
}
}
void readGraph()
{
int i = 0;
FILE *fp = fopen("matris.txt", "r");
while(fscanf(fp, "%d %d %d %d %d %d",
&graph[i][0],
&graph[i][1],
&graph[i][2],
&graph[i][3],
&graph[i][4],
&graph[i][5]) !=EOF){
i = i + 1;
}
}
int main()
{
readGraph();
BFS(2);
return 0;
}
0 1 1 0 0 0
1 0 0 1 0 0
1 0 0 1 0 0
0 1 1 0 1 0
0 0 0 1 0 1
0 0 0 0 1 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment