Created
April 13, 2020 07:54
-
-
Save ioanzicu/e8b135e1a2ae44a0a34689964fe4e55d to your computer and use it in GitHub Desktop.
Breadth First Search and Depth First Search
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
#include<stdio.h> | |
#include<stdlib.h> | |
// QUEUE | |
struct Node { | |
int data; | |
struct Node *next; | |
} *front = NULL, *rear = NULL; | |
void enqueue(int value) { | |
struct Node *t; | |
t = (struct Node *)malloc(sizeof(struct Node)); | |
if (t == NULL) | |
printf("Queue is FULL\n"); | |
else { | |
t->data = value; | |
t->next = NULL; | |
if (front == NULL) | |
front = rear = t; | |
else { | |
rear->next = t; | |
rear = t; | |
} | |
} | |
} | |
int dequeue() { | |
int value = -1; | |
struct Node *t; | |
if (front == NULL) | |
printf("Queue is Empty\n"); | |
else { | |
value = front->data; | |
t = front; | |
front = front->next; | |
free(t); | |
} | |
return value; | |
} | |
int isEmpty() { | |
return front == NULL; | |
} | |
// Breadth First Search | |
void BFS(int G[][7], int start, int n) { | |
int i = start, j; | |
int visited[7] = {0}; | |
printf("%d ", i); | |
visited[i] = 1; | |
enqueue(i); | |
while (!isEmpty()) { | |
i = dequeue(); | |
for (j = 1; j < n; ++j) { | |
if (G[i][j] == 1 && visited[j] == 0) { | |
printf("%d ", j); | |
visited[j] = 1; | |
enqueue(j); | |
} | |
} | |
} | |
} | |
// Depth First Search | |
void DFS(int G[][7], int start, int n) { | |
static int visited[7] = {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) | |
DFS(G, j, n); | |
} | |
} | |
} | |
int main() { | |
int G[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(G, 1, 7); | |
printf("\n"); | |
DFS(G, 1, 7); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment