0% found this document useful (0 votes)
20 views

Adsa Lab Manual

ADSA LAB MANUAL

Uploaded by

SwethaRouthu
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Adsa Lab Manual

ADSA LAB MANUAL

Uploaded by

SwethaRouthu
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 44

EXRCISE-1

AIM: Construct an AVL tree for a given set of elements which are stored in a file. And implement
insert and delete operation on the constructed tree. Write contents of tree into a new file using in-
order.

PROGRAM:
/*

* AVL Tree Program in C

*/

#include<stdio.h>

#include<stdlib.h>

// structure of the tree node

struct node

int data;

struct node* left;

struct node* right;

int ht;

};

// global initialization of root node

struct node* root = NULL;

// function prototyping

struct node* create(int);

struct node* insert(struct node*, int);

struct node* delete(struct node*, int);

struct node* search(struct node*, int);

struct node* rotate_left(struct node*);

struct node* rotate_right(struct node*);


int balance_factor(struct node*);

int height(struct node*);

void inorder(struct node*);

void preorder(struct node*);

void postorder(struct node*);

int main()

int user_choice, data;

char user_continue = 'y';

struct node* result = NULL;

while (user_continue == 'y' || user_continue == 'Y')

printf("\n\n------- AVL TREE --------\n");

printf("\n1. Insert");

printf("\n2. Delete");

printf("\n3. Search");

printf("\n4. Inorder");

printf("\n5. Preorder");

printf("\n6. Postorder");

printf("\n7. EXIT");

printf("\n\nEnter Your Choice: ");

scanf("%d", &user_choice);

switch(user_choice)

case 1:

printf("\nEnter data: ");

scanf("%d", &data);
root = insert(root, data);

break;

case 2:

printf("\nEnter data: ");

scanf("%d", &data);

root = delete(root, data);

break;

case 3:

printf("\nEnter data: ");

scanf("%d", &data);

result = search(root, data);

if (result == NULL)

printf("\nNode not found!");

else

printf("\n Node found");

break;

case 4:

inorder(root);

break;

case 5:

preorder(root);

break;

case 6:
postorder(root);

break;

case 7:

printf("\n\tProgram Terminated\n");

return 1;

default:

printf("\n\tInvalid Choice\n");

printf("\n\nDo you want to continue? ");

scanf(" %c", &user_continue);

return 0;

// creates a new tree node

struct node* create(int data)

struct node* new_node = (struct node*) malloc (sizeof(struct node));

// if a memory error has occurred

if (new_node == NULL)

printf("\nMemory can't be allocated\n");

return NULL;

new_node->data = data;

new_node->left = NULL;
new_node->right = NULL;

return new_node;

// rotates to the left

struct node* rotate_left(struct node* root)

struct node* right_child = root->right;

root->right = right_child->left;

right_child->left = root;

// update the heights of the nodes

root->ht = height(root);

right_child->ht = height(right_child);

// return the new node after rotation

return right_child;

// rotates to the right

struct node* rotate_right(struct node* root)

struct node* left_child = root->left;

root->left = left_child->right;

left_child->right = root;

// update the heights of the nodes

root->ht = height(root);

left_child->ht = height(left_child);

// return the new node after rotation


return left_child;

// calculates the balance factor of a node

int balance_factor(struct node* root)

int lh, rh;

if (root == NULL)

return 0;

if (root->left == NULL)

lh = 0;

else

lh = 1 + root->left->ht;

if (root->right == NULL)

rh = 0;

else

rh = 1 + root->right->ht;

return lh - rh;

// calculate the height of the node

int height(struct node* root)

int lh, rh;

if (root == NULL)

return 0;

if (root->left == NULL)

lh = 0;

else
lh = 1 + root->left->ht;

if (root->right == NULL)

rh = 0;

else

rh = 1 + root->right->ht;

if (lh > rh)

return (lh);

return (rh);

// inserts a new node in the AVL tree

struct node* insert(struct node* root, int data)

if (root == NULL)

struct node* new_node = create(data);

if (new_node == NULL)

return NULL;

root = new_node;

else if (data > root->data)

// insert the new node to the right

root->right = insert(root->right, data);

// tree is unbalanced, then rotate it

if (balance_factor(root) == -2)

{
if (data > root->right->data)

root = rotate_left(root);

else

root->right = rotate_right(root->right);

root = rotate_left(root);

else

// insert the new node to the left

root->left = insert(root->left, data);

// tree is unbalanced, then rotate it

if (balance_factor(root) == 2)

if (data < root->left->data)

root = rotate_right(root);

else

root->left = rotate_left(root->left);

root = rotate_right(root);

// update the heights of the nodes


root->ht = height(root);

return root;

// deletes a node from the AVL tree

struct node * delete(struct node *root, int x)

struct node * temp = NULL;

if (root == NULL)

return NULL;

if (x > root->data)

root->right = delete(root->right, x);

if (balance_factor(root) == 2)

if (balance_factor(root->left) >= 0)

root = rotate_right(root);

else

root->left = rotate_left(root->left);

root = rotate_right(root);

else if (x < root->data)


{

root->left = delete(root->left, x);

if (balance_factor(root) == -2)

if (balance_factor(root->right) <= 0)

root = rotate_left(root);

else

root->right = rotate_right(root->right);

root = rotate_left(root);

else

if (root->right != NULL)

temp = root->right;

while (temp->left != NULL)

temp = temp->left;

root->data = temp->data;

root->right = delete(root->right, temp->data);

if (balance_factor(root) == 2)

if (balance_factor(root->left) >= 0)

root = rotate_right(root);

}
else

root->left = rotate_left(root->left);

root = rotate_right(root);

else

return (root->left);

root->ht = height(root);

return (root);

// search a node in the AVL tree

struct node* search(struct node* root, int key)

if (root == NULL)

return NULL;

if(root->data == key)

return root;

if(key > root->data)

{
search(root->right, key);

else

search(root->left, key);

return 0;

// inorder traversal of the tree

void inorder(struct node* root)

if (root == NULL)

return;

inorder(root->left);

printf("%d ", root->data);

inorder(root->right);

// preorder traversal of the tree

void preorder(struct node* root)

if (root == NULL)

return;

printf("%d ", root->data);


preorder(root->left);

preorder(root->right);

// postorder traversal of the tree

void postorder(struct node* root)

if (root == NULL)

return;

postorder(root->left);

postorder(root->right);

printf("%d ", root->data);

OUTPUT:

------- AVL TREE --------

1. Insert

2. Delete

3. Search

4. Inorder

5. Preorder

6. Postorder

7. EXIT

Enter Your Choice: 1


Enter data: 12

Do you want to continue? y

------- AVL TREE --------

1. Insert

2. Delete

3. Search

4. Inorder

5. Preorder

6. Postorder

7. EXIT

Enter Your Choice: 1

Enter data: 45

Do you want to continue? y

------- AVL TREE --------

1. Insert

2. Delete

3. Search

4. Inorder

5. Preorder
6. Postorder

7. EXIT

Enter Your Choice: 4

12 45

Do you want to continue? y

------- AVL TREE --------

1. Insert

2. Delete

3. Search

4. Inorder

5. Preorder

6. Postorder

7. EXIT

Enter Your Choice: 2

Enter data: 12

Do you want to continue? y

------- AVL TREE --------

1. Insert

2. Delete
3. Search

4. Inorder

5. Preorder

6. Postorder

7. EXIT

Enter Your Choice: 4

45

EXERCISE-2
AIM: Construct B-Tree an order of 5 with a set of 100 random elements stored in array. Implement
searching, insertion and deletion operations.

PROGRAM:
// C Program for B trees

#include <stdio.h>

#include <stdlib.h>

#define MAX 4

#define MIN 2

struct btreeNode {

int val[MAX + 1], count;

struct btreeNode *link[MAX + 1];

};

struct btreeNode *root;

/* creating new node */

struct btreeNode * createNode(int val, struct btreeNode *child) {

struct btreeNode *newNode;


newNode = (struct btreeNode *)malloc(sizeof(struct btreeNode));

newNode->val[1] = val;

newNode->count = 1;

newNode->link[0] = root;

newNode->link[1] = child;

return newNode;

/* Places the value in appropriate position */

void addValToNode(int val, int pos, struct btreeNode *node,

struct btreeNode *child) {

int j = node->count;

while (j > pos) {

node->val[j + 1] = node->val[j];

node->link[j + 1] = node->link[j];

j--;

node->val[j + 1] = val;

node->link[j + 1] = child;

node->count++;

/* split the node */

void splitNode (int val, int *pval, int pos, struct btreeNode *node,

struct btreeNode *child, struct btreeNode **newNode) {

int median, j;

if (pos > MIN)

median = MIN + 1;

else

median = MIN;
*newNode = (struct btreeNode *)malloc(sizeof(struct btreeNode));

j = median + 1;

while (j <= MAX) {

(*newNode)->val[j - median] = node->val[j];

(*newNode)->link[j - median] = node->link[j];

j++;

node->count = median;

(*newNode)->count = MAX - median;

if (pos <= MIN) {

addValToNode(val, pos, node, child);

} else {

addValToNode(val, pos - median, *newNode, child);

*pval = node->val[node->count];

(*newNode)->link[0] = node->link[node->count];

node->count--;

/* sets the value val in the node */

int setValueInNode(int val, int *pval,

struct btreeNode *node, struct btreeNode **child) {

int pos;

if (!node) {

*pval = val;

*child = NULL;

return 1;

}
if (val < node->val[1]) {

pos = 0;

} else {

for (pos = node->count;

(val < node->val[pos] && pos > 1); pos--);

if (val == node->val[pos]) {

printf("Duplicates not allowed\n");

return 0;

if (setValueInNode(val, pval, node->link[pos], child)) {

if (node->count < MAX) {

addValToNode(*pval, pos, node, *child);

} else {

splitNode(*pval, pval, pos, node, *child, child);

return 1;

return 0;

/* insert val in B-Tree */

void insertion(int val) {

int flag, i;

struct btreeNode *child;

flag = setValueInNode(val, &i, root, &child);

if (flag)

root = createNode(i, child);

}
/* copy successor for the value to be deleted */

void copySuccessor(struct btreeNode *myNode, int pos) {

struct btreeNode *dummy;

dummy = myNode->link[pos];

for (;dummy->link[0] != NULL;)

dummy = dummy->link[0];

myNode->val[pos] = dummy->val[1];

/* removes the value from the given node and rearrange values */

void removeVal(struct btreeNode *myNode, int pos) {

int i = pos + 1;

while (i <= myNode->count) {

myNode->val[i - 1] = myNode->val[i];

myNode->link[i - 1] = myNode->link[i];

i++;

myNode->count--;

/* shifts value from parent to right child */

void doRightShift(struct btreeNode *myNode, int pos) {

struct btreeNode *x = myNode->link[pos];

int j = x->count;

while (j > 0) {

x->val[j + 1] = x->val[j];

x->link[j + 1] = x->link[j];
}

x->val[1] = myNode->val[pos];

x->link[1] = x->link[0];

x->count++;

x = myNode->link[pos - 1];

myNode->val[pos] = x->val[x->count];

myNode->link[pos] = x->link[x->count];

x->count--;

return;

/* shifts value from parent to left child */

void doLeftShift(struct btreeNode *myNode, int pos) {

int j = 1;

struct btreeNode *x = myNode->link[pos - 1];

x->count++;

x->val[x->count] = myNode->val[pos];

x->link[x->count] = myNode->link[pos]->link[0];

x = myNode->link[pos];

myNode->val[pos] = x->val[1];

x->link[0] = x->link[1];

x->count--;

while (j <= x->count) {

x->val[j] = x->val[j + 1];

x->link[j] = x->link[j + 1];

j++;

}
return;

/* merge nodes */

void mergeNodes(struct btreeNode *myNode, int pos) {

int j = 1;

struct btreeNode *x1 = myNode->link[pos], *x2 = myNode->link[pos - 1];

x2->count++;

x2->val[x2->count] = myNode->val[pos];

x2->link[x2->count] = myNode->link[0];

while (j <= x1->count) {

x2->count++;

x2->val[x2->count] = x1->val[j];

x2->link[x2->count] = x1->link[j];

j++;

j = pos;

while (j < myNode->count) {

myNode->val[j] = myNode->val[j + 1];

myNode->link[j] = myNode->link[j + 1];

j++;

myNode->count--;

free(x1);

/* adjusts the given node */

void adjustNode(struct btreeNode *myNode, int pos) {


if (!pos) {

if (myNode->link[1]->count > MIN) {

doLeftShift(myNode, 1);

} else {

mergeNodes(myNode, 1);

} else {

if (myNode->count != pos) {

if(myNode->link[pos - 1]->count > MIN) {

doRightShift(myNode, pos);

} else {

if (myNode->link[pos + 1]->count > MIN) {

doLeftShift(myNode, pos + 1);

} else {

mergeNodes(myNode, pos);

} else {

if (myNode->link[pos - 1]->count > MIN)

doRightShift(myNode, pos);

else

mergeNodes(myNode, pos);

/* delete val from the node */

int delValFromNode(int val, struct btreeNode *myNode) {

int pos, flag = 0;

if (myNode) {

if (val < myNode->val[1]) {


pos = 0;

flag = 0;

} else {

for (pos = myNode->count;

(val < myNode->val[pos] && pos > 1); pos--);

if (val == myNode->val[pos]) {

flag = 1;

} else {

flag = 0;

if (flag) {

if (myNode->link[pos - 1]) {

copySuccessor(myNode, pos);

flag = delValFromNode(myNode->val[pos], myNode->link[pos]);

if (flag == 0) {

printf("Given data is not present in B-Tree\n");

} else {

removeVal(myNode, pos);

} else {

flag = delValFromNode(val, myNode->link[pos]);

if (myNode->link[pos]) {

if (myNode->link[pos]->count < MIN)

adjustNode(myNode, pos);

return flag;

}
/* delete val from B-tree */

void deletion(int val, struct btreeNode *myNode) {

struct btreeNode *tmp;

if (!delValFromNode(val, myNode)) {

printf("Given value is not present in B-Tree\n");

return;

} else {

if (myNode->count == 0) {

tmp = myNode;

myNode = myNode->link[0];

free(tmp);

root = myNode;

return;

/* search val in B-Tree */

void searching(int val, int *pos, struct btreeNode *myNode) {

if (!myNode) {

return;

if (val < myNode->val[1]) {

*pos = 0;

} else {

for (*pos = myNode->count;

(val < myNode->val[*pos] && *pos > 1); (*pos)--);

if (val == myNode->val[*pos]) {

printf("Given data %d is present in B-Tree", val);


return;

searching(val, pos, myNode->link[*pos]);

return;

/* B-Tree Traversal */

void traversal(struct btreeNode *myNode) {

int i;

if (myNode) {

for (i = 0; i < myNode->count; i++) {

traversal(myNode->link[i]);

printf("%d ", myNode->val[i + 1]);

traversal(myNode->link[i]);

int main() {

int val, ch;

while (1) {

printf("1. Insertion\t2. Deletion\n");

printf("3. Searching\t4. Traversal\n");

printf("5. Exit\nEnter your choice:");

scanf("%d", &ch);

switch (ch) {

case 1:

printf("Enter your input:");

scanf("%d", &val);

insertion(val);
break;

case 2:

printf("Enter the element to delete:");

scanf("%d", &val);

deletion(val, root);

break;

case 3:

printf("Enter the element to search:");

scanf("%d", &val);

searching(val, &ch, root);

break;

case 4:

traversal(root);

break;

case 5:

exit(0);

default:

printf("U have entered wrong option!!\n");

break;

printf("\n");

OUTPUT:
1. Insertion 2. Deletion
3. Searching 4. Traversal
5. Exit
Enter your choice:1
Enter your input:12
1. Insertion 2. Deletion
3. Searching 4. Traversal
5. Exit
Enter your choice:1
Enter your input:10

1. Insertion 2. Deletion
3. Searching 4. Traversal
5. Exit
Enter your choice:1
Enter your input:1

1. Insertion 2. Deletion
3. Searching 4. Traversal
5. Exit
Enter your choice:4
1 10 12 45
1. Insertion 2. Deletion
3. Searching 4. Traversal
5. Exit
Enter your choice:2
Enter the element to delete:10

1. Insertion 2. Deletion
3. Searching 4. Traversal
5. Exit
Enter your choice:4
1 12 45
EXERCISE-3
AIM: Construct Min and Max Heap using arrays, delete any element and display the content of the
Heap.

PROGRAM:
// C Program for B trees

#include <stdio.h>

#define MAX_SIZE 100

struct Heap { int arr[MAX_SIZE]; int size; };

// Function to swap two elements in the heap

void swap(int *a, int *b)

int temp = *a;

*a = *b;

*b = temp;

// Function to heapify the array

void heapify(struct Heap *h, int i, int type)

int largest = i;

int left = 2 * i + 1;

int right = 2 * i + 2;

if (type == 1) {

// Max Heap
if (left < h->size && h->arr[left] > h->arr[largest])

largest = left;

if (right < h->size && h->arr[right] > h->arr[largest])

largest = right;

else { // Min Heap

if (left < h->size && h->arr[left] < h->arr[largest])

largest = left;

if (right < h->size && h->arr[right] < h->arr[largest])

largest = right;

if (largest != i)

{ swap(&h->arr[i], &h->arr[largest]);

heapify(h, largest, type);

// Function to insert an element into the heap

void insert(struct Heap *h, int value, int type)

if (h->size == MAX_SIZE)

{ printf("Heap is full, cannot insert more elements.\n");

return; }

h->size++;

int i = h->size - 1;

h->arr[i] = value;

while (i != 0 && ((type == 1 && h->arr[(i - 1) / 2] < h->arr[i]) || (type == 0 && h->arr[(i - 1) / 2] > h-
>arr[i])))
{

swap(&h->arr[i],

&h->arr[(i - 1) / 2]);

i = (i - 1) / 2; }

// Function to delete an element from the heap

void deleteElement(struct Heap *h, int value, int type)

int i;

for (i = 0; i < h->size; i++)

if (h->arr[i] == value)

break;

if (i == h->size)

{ printf("Element not found in the heap.\n");

return;

h->arr[i] = h->arr[h->size - 1];

h->size--;

if (type == 1) // Max Heap

heapify(h, i, 1);

else // Min Heap

heapify(h, i, 0);

}
// Function to display the content of the heap

void display(struct Heap *h)

int i;

printf("Heap elements: ");

for (i = 0; i < h->size; i++)

{ printf("%d ", h->arr[i]);

printf("\n");

int main() {

struct Heap minHeap, maxHeap; minHeap.size = 0; maxHeap.size = 0;

// Insert elements into the heaps

insert(&minHeap, 5, 0); // Insert into Min Heap

insert(&minHeap, 3, 0);

insert(&minHeap, 17, 0);

insert(&minHeap, 10, 0);

insert(&minHeap, 84, 0);

insert(&maxHeap, 5, 1); // Insert into Max Heap

insert(&maxHeap, 3, 1);

insert(&maxHeap, 17, 1);

insert(&maxHeap, 10, 1);

insert(&maxHeap, 84, 1);

// Display the heaps

printf("Min Heap:\n");

display(&minHeap);

printf("Max Heap:\n");
display(&maxHeap);

// Delete an element from the heaps

deleteElement(&minHeap, 17, 0);

// Delete from Min Heap

deleteElement(&maxHeap, 17, 1); // Delete from Max Heap

// Display the heaps after deletion

printf("Min Heap after deletion:\n");

display(&minHeap);

printf("Max Heap after deletion:\n");

display(&maxHeap);

OUTPUT:
Min Heap:

Heap elements: 3 5 17 10 84

Max Heap:

Heap elements: 84 17 5 3 10

Min Heap after deletion:

Heap elements: 3 5 84 10

Max Heap after deletion:

Heap elements: 84 10 5 3
EXERCISE-4
AIM: Implement BFT and DFT for given graph, when graph is represented by a) Adjacency Matrix b)
Adjacency Lists

PROGRAM:
a)BFT and DFT for Adjacency matrix

#include <stdio.h>

#include<stdlib.h>

int a[10][10],visited[10],n;

void bfs (int u)

int v,f,r,q[10];

f=0,r=-1;

printf("the no of nodes visited from %d",u,"\n");

q[++r]=u;

visited[u]=1;

while(f<=r)

u=q[f++];

for(v=0;v<=n;v++)

if(a[u][v]==1)

if(visited[v]==0)

printf(" %d", v,"\n");

visited[v]=1;

q[r++]=v;

}
}

void dfs(int v)

int w;

visited[v]=1;

printf(" %d",v);

for(w=0;w<=n;w++)

if(a[v][w]==1&&visited[w]==0)

dfs(w);

void main()

int choice,source,s1,i,j,done;

printf("graph traversal using adjacency matrix\n");

printf("enter the number of nodes\n");

scanf("%d",&n);

printf("enter the adjacency matrix");

for(i=0;i<n;i++)

for(j=0;j<n;j++)

scanf("%d",&a[i][j]);

for(;;)

{
printf("\n1.reachable node using bfs\n2.reachable node using dfs\n3.exit\nEnter your choice\
n");

scanf("%d",&choice);

switch(choice)

case 1:printf("enter the source node\n");

scanf("%d",&s1);

bfs(s1);

break;

case 2:for(source=0;source<n;source++)

for(i=0;i<n;i++)

visited[i]=0;

printf("\nreachable node from %d is",source,"\n");

dfs(source);

break;

case 3:exit(0);

OUTPUT:

graph traversal using adjacency matrix

enter the number of nodes

3
enter the adjacency matrix

111

111

111

1.reachable node using bfs

2.reachable node using dfs

3.exit

Enter your choice

enter the source node

the no of nodes visited from 1 0 2

1.reachable node using bfs

2.reachable node using dfs

3.exit

Enter your choice

reachable node from 0 is 0 1 2

reachable node from 1 is 1 0 2

reachable node from 2 is 2 0 1

b) BFT and DFT using adjacency list

PROGRAM:

#include <stdio.h>

#include <stdlib.h>

#include <stdbool.h>

#define MAX_VERTICES 50
// Structure for a node in the adjacency list

struct Node {

int data;

struct Node* next;

};

// Structure for the adjacency list

struct List {

struct Node* head;

};

// Structure for the graph

struct Graph {

int vertices;

struct List* array;

};

typedef struct Graph_t {

// No. of vertices

int V;

bool adj[MAX_VERTICES][MAX_VERTICES];

} Graph;

Graph* Graph_create(int V)

int i,j;

Graph* g = malloc(sizeof(Graph));

g->V = V;

for (i = 0; i < V; i++) {


for (j = 0; j < V; j++) {

g->adj[i][j] = false;

return g;

// Destructor

void Graph_destroy(Graph* g) { free(g); }

// Function to add an edge to graph

void Graph_addEdge(Graph* g, int v, int w)

// Add w to v’s list.

g->adj[v][w] = true;

// Prints BFS traversal from a given source s

void Graph_BFS(Graph* g, int s)

int i,adjacent;

// Mark all the vertices as not visited

bool visited[MAX_VERTICES];

for (i = 0; i < g->V; i++) {

visited[i] = false;

// Create a queue for BFS

int queue[MAX_VERTICES];

int front = 0, rear = 0;


// Mark the current node as visited and enqueue it

visited[s] = true;

queue[rear++] = s;

while (front != rear) {

// Dequeue a vertex from queue and print it

s = queue[front++];

printf("%d ", s);

// Get all adjacent vertices of the dequeued

// vertex s.

// If an adjacent has not been visited,

// then mark it visited and enqueue it

for (adjacent = 0; adjacent < g->V;

adjacent++) {

if (g->adj[s][adjacent] && !visited[adjacent]) {

visited[adjacent] = true;

queue[rear++] = adjacent;

// Function to create a new node

struct Node* createNode(int data) {

struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));

newNode->data = data;

newNode->next = NULL;

return newNode;
}

// Function to create a graph with a given number of vertices

struct Graph* createGraph(int vertices) {

int i;

struct Graph* graph = (struct Graph*)malloc(sizeof(struct Graph));

graph->vertices = vertices;

graph->array = (struct List*)malloc(vertices * sizeof(struct List));

for (i = 0; i < vertices; i++) {

graph->array[i].head = NULL;

return graph;

// Function to add an edge to the graph

void addEdge(struct Graph* graph, int src, int dest) {

struct Node* newNode = createNode(dest);

newNode->next = graph->array[src].head;

graph->array[src].head = newNode;

// Uncomment the following code to make the graph undirected

/*

newNode = createNode(src);

newNode->next = graph->array[dest].head;

graph->array[dest].head = newNode;

*/

// Function to perform Depth First Search (DFS) from a given vertex


void DFS(struct Graph* graph, int vertex, bool visited[]) {

visited[vertex] = true;

printf("%d ", vertex);

struct Node* currentNode = graph->array[vertex].head;

while (currentNode) {

int adjacentVertex = currentNode->data;

if (!visited[adjacentVertex]) {

DFS(graph, adjacentVertex, visited);

currentNode = currentNode->next;

// Function to perform DFS traversal from a given vertex in a specified order

void DFSTraversal(struct Graph* graph, int* order, int orderSize) {

int i;

bool* visited = (bool*)malloc(graph->vertices * sizeof(bool));

for (i = 0; i < graph->vertices; i++) {

visited[i] = false;

for (i = 0; i < orderSize; i++) {

if (!visited[order[i]]) {

DFS(graph, order[i], visited);

int main() {

int vertices = 4;

struct Graph* graph = createGraph(vertices);


addEdge(graph, 2, 0);

addEdge(graph, 0, 2);

addEdge(graph, 1, 2);

addEdge(graph, 0, 1);

addEdge(graph, 3, 3);

addEdge(graph, 1, 3);

int order[] = {2, 0, 1, 3};

int orderSize = sizeof(order) / sizeof(order[0]);

printf("Following is Depth First Traversal (starting from vertex 2):\n");

DFSTraversal(graph, order, orderSize);

Graph* g = Graph_create(4);

Graph_addEdge(g, 0, 1);

Graph_addEdge(g, 0, 2);

Graph_addEdge(g, 1, 2);

Graph_addEdge(g, 2, 0);

Graph_addEdge(g, 2, 3);

Graph_addEdge(g, 3, 3);

printf("\nFollowing is Breadth First Traversal "

"(starting from vertex 2) \n");

Graph_BFS(g, 2);

Graph_destroy(g);

return 0;

OUTPUT:
Following is Depth First Traversal (starting from vertex 2):

2013

Following is Breadth First Traversal (starting from vertex 2):


2031

You might also like