chore(C): add breadth-first search and depth-first search (#644)

Co-authored-by: Rahul Rajeev Pillai <66192267+Ashborn-SM@users.noreply.github.com>
pull/648/head
Anish 2021-12-08 19:48:05 +05:30 committed by GitHub
parent 62f1cfe0cd
commit bf2b27489d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 150 additions and 0 deletions

View File

@ -16,6 +16,8 @@
## Graphs ## Graphs
- [Prim's Algorithm](graphs/Prim's-algorithm.c) - [Prim's Algorithm](graphs/Prim's-algorithm.c)
- [Breadth First Search](graphs/breadth-first-search.c)
- [Depth First Search](graphs/depth-first-search.c)
## Linked Lists ## Linked Lists

View File

@ -0,0 +1,105 @@
/* Breadth-first search (BFS) is an algorithm for searching a tree data structure for a node that
satisfies a given property. It starts at the tree root and explores all nodes at the present depth prior
to moving on to the nodes at the next depth level.*/
#include <stdio.h>
#include <stdlib.h>
// Adjacency Matrix
int G[][5] = {
{0, 1, 1, 1, 0},
{1, 0, 1, 0, 0},
{1, 1, 0, 0, 1},
{1, 0, 0, 0, 0},
{0, 0, 1, 0, 0}};
int start = 0, n = 5;
// Node Structure
struct Node
{
int data;
struct Node *next;
};
struct Node *front = NULL;
struct Node *rear = NULL;
void enqueue(int x)
{
struct Node *temp = malloc(sizeof(*temp));
temp->data = x;
temp->next = NULL;
if (front == NULL)
{
front = temp;
rear = temp;
}
else
{
rear->next = temp;
rear = temp;
}
}
int dequeue()
{
int x = -1;
if (front == NULL)
{
printf("Queue is empty\n");
}
else
{
struct Node *temp = front;
x = temp->data;
front = front->next;
free(temp);
}
return x;
}
int isEmpty()
{
if (front == NULL)
{
return 1;
}
else
{
return 0;
}
}
void BFSTraversal(int G[][5], int start, int n)
{
int i, j;
int visited[5] = {0};
enqueue(start);
visited[start] = 1;
while (!isEmpty())
{
i = dequeue();
printf("%d ", i);
for (j = 1; j < n; j++)
{
if (G[i][j] == 1 && visited[j] == 0)
{
enqueue(j);
visited[j] = 1;
}
}
}
}
int main()
{
BFSTraversal(G, start, n);
return 0;
}
/*
Output:
0 1 2 3 4
*/

View File

@ -0,0 +1,43 @@
/* Depth-first search (DFS) is an algorithm for traversing or searching tree or graph data structures.
The algorithm starts at the root node (selecting some arbitrary node as the root node in the case of a graph) and
explores as far as possible along each branch before backtracking.*/
#include <stdio.h>
// Adjacency Matrix
int G[][5] = {
{0, 1, 1, 1, 0},
{1, 0, 1, 0, 0},
{1, 1, 0, 0, 1},
{1, 0, 0, 0, 0},
{0, 0, 1, 0, 0}};
int start = 0, n = 5;
void DFSTraversal(int G[][5], int start, int n)
{
static int visited[5] = {0};
int j;
if (visited[start] == 0)
{
printf("%d ", start);
visited[start] = 1;
for (j = 1; j < n; j++)
{
if (G[start][j] == 1 && visited[j] == 0){
DFSTraversal(G, j, n);
}
}
}
}
int main()
{
DFSTraversal(G, start, n);
return 0;
}
/*
Output:
0 1 2 4 3
*/