0% found this document useful (0 votes)
23 views60 pages

DSA-II Practical Lab book Solutions.docx

The document outlines assignments related to Binary Search Trees (BST) and their implementations in C programming. It includes tasks such as creating a BST library, performing various operations like insertion, searching, and traversals, as well as additional assignments involving heapsort and graph representations using adjacency matrices. The document provides code snippets and instructions for each assignment, focusing on the use of recursion and data structures.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views60 pages

DSA-II Practical Lab book Solutions.docx

The document outlines assignments related to Binary Search Trees (BST) and their implementations in C programming. It includes tasks such as creating a BST library, performing various operations like insertion, searching, and traversals, as well as additional assignments involving heapsort and graph representations using adjacency matrices. The document provides code snippets and instructions for each assignment, focusing on the use of recursion and data structures.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 60

Assignment 1: Binary Search Tree and Traversals

Set A
a) Implement a Binary search tree (BST) library (btree.h) with operations –
create, search, insert, inorder, preorder and postorder. Write a menu driven
program that performs the above operations.
#include<stdio.h>
#include<stdlib.h>
struct bst
{
int data;
struct bst *lchild,*rchild;
}node;
int cnt=0,leafcnt=0,nleafcnt=0;
struct bst *create()
{
struct bst *temp=(struct bst*)malloc(sizeof(struct bst));
temp->lchild=NULL;
temp->rchild=NULL;
return temp;
}
void insert(struct bst *r, struct bst *new1)
{
if(new1->data < r->data)
{
if(r->lchild==NULL)
r->lchild=new1;
else
insert(r->lchild,new1);
}
if(new1->data > r->data)
{
if(r->rchild==NULL)
r->rchild=new1;
else
insert(r->rchild,new1);
}
}

struct bst *search(struct bst *r, int key)


{
struct bst *temp;
temp=r;
while(temp!=NULL)
{
if(temp->data==key)
return temp;
if(key < temp->data)
temp=temp->lchild;
else
temp=temp->rchild;
}
return NULL;
}

int count(struct bst *temp)


{
if(temp!=NULL)
{
cnt++;
count(temp->lchild);
count(temp->rchild);
}
return cnt;
}
int countleaf(struct bst *temp)
{
if(temp!=NULL)
{
if(temp->lchild==NULL && temp->rchild==NULL)
leafcnt++;
countleaf(temp->lchild);
countleaf(temp->rchild);
}
return leafcnt;
}

int countnleaf(struct bst *temp)


{
if(temp!=NULL)
{
if(temp->lchild!=NULL || temp->rchild!=NULL)
nleafcnt++;
countnleaf(temp->lchild);
countnleaf(temp->rchild);
}
return nleafcnt;
}

void inorder(struct bst *temp)


{
if(temp!=NULL)
{
inorder(temp->lchild);
printf("%d\t",temp->data);
inorder(temp->rchild);
}
}

void postorder(struct bst *temp)


{
if(temp!=NULL)
{
postorder(temp->lchild);
postorder(temp->rchild);
printf("%d\t",temp->data);
}
}

void preorder(struct bst *temp)


{
if(temp!=NULL)
{
printf("%d\t",temp->data);
preorder(temp->lchild);
preorder(temp->rchild);
}
}

void inorder_n(struct bst *r)


{
struct bst *stack[100];
int top=-1;
if(r!=NULL)
{
top++;
stack[top]=r;
r=r->lchild;
while(top>=0)
{

while(r!=NULL)
{
top++;
stack[top]=r;
r=r->lchild;
}
r=stack[top];
top--;
printf("%d\t",r->data);
r=r->rchild;

if(r!=NULL)
{
top++;
stack[top]=r;
r=r->lchild;
}
}
}
}
Save this above code in the stack library file as btree.h
#include<stdio.h>
#include<stdlib.h>
#include "btree.h"
int main()
{
int ch,n,i,value,cnt;
struct bst *newnode,*root,*temp;
root=NULL;
while(1)
{
printf("\n---Binary Search Tree---\n");
printf("1.Insert\n");
printf("2.Search\n");
printf("3.Count Total Nodes\n");
printf("4.Count Leaf Nodes\n");
printf("5.Count Non Leaf Nodes\n");
printf("6.Inorder Traversal (Recursive)\n");
printf("7.Postorder Traversal (Recursive)\n");
printf("8.Preorder Traversal (Recursive)\n");
printf("9.Inorder Traversal (Non Recursive\n");
printf("10.Exit\n");
printf("Enter your choice:");
scanf("%d",&ch);
switch(ch)
{
case 1: printf("\nHow many nodes to create:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
newnode=create();
printf("\nEnter the node data:");
scanf("%d",&newnode->data);
if(root==NULL)
root=newnode;
else
insert(root,newnode);
}
break;
case 2: printf("\nEnter the node value to be searched:");
scanf("%d",&value);
temp=search(root,value);
if(temp==NULL)
printf("\nNode Not Found\n");
else
printf("\nNode Found\n");
break;
case 3: cnt=count(root);
printf("\nTotal Nodes=%d\n",cnt);
break;
case 4: cnt=countleaf(root);
printf("\nTotal Leaf Nodes=%d\n",cnt);
break;
case 5: cnt=countnleaf(root);
printf("\nTotal Non Leaf Nodes=%d\n",cnt);
break;
case 6: printf("\nInorder Traversal=");
inorder(root);
break;
case 7: printf("\nPostorder Traversal=");
postorder(root);
break;
case 8: printf("\nPreorder Traversal=");
preorder(root);
break;
case 9: printf("\nInorder Traversal=");
inorder_n(root);
break;
case 10: exit(0);
default: printf("\nInvalid Choice\n");
}
}
}

b) Write a program which uses binary search tree library and counts the total
nodes and total leaf nodes in the tree.
int count(T) – returns the total number of nodes from BST
int countLeaf(T) – returns the total number of leaf nodes from BST

#include<stdio.h>
#include<stdlib.h>
#include "btree.h"
int main()
{
int ch,n,i,value,cnt;
struct bst *newnode,*root,*temp;
root=NULL;
while(1)
{
printf("\n---Binary Search Tree---\n");
printf("1.Insert\n");
printf("2.Search\n");
printf("3.Count Total Nodes\n");
printf("4.Count Leaf Nodes\n");
printf("5.Count Non Leaf Nodes\n");
printf("6.Exit\n");
printf("Enter your choice:");
scanf("%d",&ch);
switch(ch)
{
case 1: printf("\nHow many nodes to create:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
newnode=create();
printf("\nEnter the node data:");
scanf("%d",&newnode->data);
if(root==NULL)
root=newnode;
else
insert(root,newnode);
}
break;
case 2: printf("\nEnter the node value to be searched:");
scanf("%d",&value);
temp=search(root,value);
if(temp==NULL)
printf("\nNode Not Found\n");
else
printf("\nNode Found\n");
break;
case 3: cnt=count(root);
printf("\nTotal Nodes=%d\n",cnt);
break;
case 4: cnt=countleaf(root);
printf("\nTotal Leaf Nodes=%d\n",cnt);
break;
case 5: cnt=countnleaf(root);
printf("\nTotal Non Leaf Nodes=%d\n",cnt);
break;
case 6: exit(0);
default: printf("\nInvalid Choice\n");
}//switch
}//while
}//main

Btree.h

#include<stdio.h>
#include<stdlib.h>
struct bst
{
int data;
struct bst *lchild,*rchild;
}node;

int cnt=0,leafcnt=0,nleafcnt=0;
//creating a new node
struct bst *create()
{
struct bst *temp=(struct bst*)malloc(sizeof(struct bst));
temp->lchild=NULL;
temp->rchild=NULL;
return temp;
}

//inserting a above created node at proper position


void insert(struct bst *r, struct bst *new1)
{
//if new node is less than parent node
if(new1->data < r->data)
{
if(r->lchild==NULL)
r->lchild=new1;
else
insert(r->lchild,new1);
}
//if new node is greater than parent node
if(new1->data > r->data)
{
if(r->rchild==NULL)
r->rchild=new1;
else
insert(r->rchild,new1);
}
}

//to search an element in Binary Search Tree


struct bst *search(struct bst *r, int key)
{
struct bst *temp;
temp=r;
while(temp!=NULL)
{
if(temp->data==key)
return temp;
if(key < temp->data)
temp=temp->lchild;
else
temp=temp->rchild;
}
return NULL;
}

//to count total number of nodes


int count(struct bst *temp)
{
if(temp!=NULL)
{
cnt++;
count(temp->lchild);
count(temp->rchild);
}
return cnt;
}

//to count total number of leaf nodes


int countleaf(struct bst *temp)
{
if(temp!=NULL)
{
if(temp->lchild==NULL && temp->rchild==NULL)
leafcnt++;
countleaf(temp->lchild);
countleaf(temp->rchild);
}
return leafcnt;
}

//to count total number of non leaf nodes


int countnleaf(struct bst *temp)
{
if(temp!=NULL)
{
if(temp->lchild!=NULL || temp->rchild!=NULL)
nleafcnt++;
countnleaf(temp->lchild);
countnleaf(temp->rchild);
}
return nleafcnt;
}

Set B
a) Write a C program which uses Binary search tree library and implements
following function with recursion:
T copy(T) – create another BST which is exact copy of BST which is passed as
parameter. int compare(T1, T2) – compares two binary search trees and returns
1 if they are equal and 0 otherwise.

Assignment 2: Binary Tree Applications

Set A

a) Write a C program which uses Binary search tree library and displays nodes
at each level, count of node at each level and total levels in the tree.

//Create a Binary Search Tree & Display Nodes level wise

#include<stdio.h>

#include<stdlib.h>

#define MAX 20

struct Btree

​ struct Btree *lchild;

​ int data;

​ struct Btree *rchild;

};

typedef struct Btree BNODE;


struct Queue

​ struct Btree *Q[MAX];

​ int front,rear;

};

typedef struct Queue QUEUE;

void Addq(QUEUE *q,BNODE *t)

​ q->Q[++q->rear]=t;

BNODE * Delq(QUEUE *q)

​ return(q->Q[++q->front]);

int isempty(QUEUE *q)

​ if(q->front==q->rear)

​ ​ return 1;

​ else

​ ​ return 0;

}
void LevelDisp(BNODE *h)

​ QUEUE q;

​ BNODE *temp;

​ int total=0,cnt=0,level=0;

​ q.front=q.rear=-1;

​ temp=h;

​ Addq(&q,temp);

​ Addq(&q,NULL);

​ while(!isempty(&q))

​ {

​ ​ temp=Delq(&q);

​ ​ if(temp==NULL)

​ ​ {

​ ​ ​ if(!isempty(&q))

​ ​ ​ {

​ ​ ​ ​ printf(" = %d Level-%d\n",cnt,level);

​ ​ ​ ​ cnt=0;

​ ​ ​ ​ level++;

​ ​ ​ ​ Addq(&q,NULL);

​ ​ ​ }

​ ​ }

​ ​ else
​ ​ {

​ ​ ​ total++;

​ ​ ​ cnt++;

​ ​ ​ printf("%d ",temp->data);

​ ​ ​ if(temp->lchild!=NULL)

​ ​ ​ ​ Addq(&q,temp->lchild);

​ ​ ​ if(temp->rchild!=NULL)

​ ​ ​ ​ Addq(&q,temp->rchild);

​ ​ }

​ }

​ printf("=%d Level-%d\n",cnt,level);

​ printf("\nTotal Nodes:%d",total);

​ printf("\nTotal Levels:%d\n",level+1);

BNODE* newNode(int data)

​ BNODE* node = (BNODE*)malloc(sizeof(BNODE));

​ node->data = data;

​ node->lchild = NULL;

​ node->rchild = NULL;

​ return(node);

}
void main()

​ BNODE *header = newNode(100);

​ header->lchild = newNode(50);

​ header->rchild = newNode(200);

​ header->rchild->lchild=newNode(150);

​ header->lchild->lchild = newNode(20);

​ header->lchild->rchild = newNode(80);

​ header->lchild->rchild->lchild = newNode(70);

​ LevelDisp(header);

Set B

a) Write a program to sort n randomly generated elements using Heapsort


method.

//C Program to sort an array based on heap sort algorithm(MAX heap)

#include <stdio.h>

void main()

int heap[10], no, i, j, c, root, temp;

printf("\n Enter no of elements :");

scanf("%d", &no);

printf("\n Enter the nos : ");

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

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

for (i = 1; i < no; i++)


{

c = i;

do

root = (c - 1) / 2;

if (heap[root] < heap[c]) /* to create MAX heap array */

temp = heap[root];

heap[root] = heap[c];

heap[c] = temp;

c = root;

} while (c != 0);

printf("Heap array : ");

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

printf("%d\t ", heap[i]);

for (j = no - 1; j >= 0; j--)

temp = heap[0];

heap[0] = heap[j]; /* swap max element with rightmost leaf element */

heap[j] = temp;

root = 0;

do
{

c = 2 * root + 1; /* left node of root element */

if ((heap[c] < heap[c + 1]) && c < j-1)

c++;

if (heap[root]<heap[c] && c<j) /* again rearrange to max heap array */

temp = heap[root];

heap[root] = heap[c];

heap[c] = temp;

root = c;

} while (c < j);

printf("\n The sorted array is : ");

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

printf("\t %d", heap[i]);

printf("\n Complexity : \n Best case = Avg case = Worst case = O(n logn) \n");

Assignment 3: Graph as Adjacency Matrix

Set A
a) Write a C program that accepts the vertices and edges of a graph and stores it as an
adjacency matrix. Display the adjacency matrix.

//Read a graph as adjacency matrix and and print it


#include<stdio.h>
int mat[10][10];
void display();
int main()
{
​ int i, j,n;
​ char reply;
​ printf("How many vertices:");
​ scanf("%d",&n);
​ for ( i = 0 ; i < n ; i++ )
​ {
​ for ( j = 0 ; j < n ; j++ )
​ {
​ printf("\n Is there edge between %d & %d ? (Y/N) :",i+1,j+1);
​ ​ scanf(" %c", &reply);
​ ​ if ( reply == 'y' || reply == 'Y' )
​ ​ mat[i][j] = 1;
​ ​ else
​ ​ mat[i][j] = 0;
​ ​ }
​ }
​ display(n);
​ return 0;
}

void display(int size)


{
​ int i,j;
​ printf("\n--------------------------------------------------------------------\n");
​ printf("\nAdjecency Matrix is:\n\n");
​ for(i=0;i<size;i++)
​ {
​ ​ for(j=0;j<size;j++)
​ ​ {
​ ​ ​ printf("%d\t",mat[i][j]);
​ ​ }
​ ​ printf("\n");
​ }
}

b) Write a C program that accepts the vertices and edges of a graph and store it as an
adjacency matrix. Implement functions to print indegree, outdegree and total degree of all
vertices of graph.

//Read a graph as adjacency matrix and and print it and find

//out indegree,outdegree and total degree of each node


#include<stdio.h>

int mat[10][10];

void display(int);

void degree(int);

int main()

​ int i, j,n;

​ char reply;

​ printf("How many vertices:");

​ scanf("%d",&n);

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

​ {

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

​ {

​ ​ printf("\n Is there edge between %d & %d ? (Y/N) :",i+1,j+1);

​ ​ scanf(" %c", &reply);

​ ​ if ( reply == 'y' || reply == 'Y' )

​ ​ mat[i][j] = 1;

​ ​ else

​ ​ mat[i][j] = 0;

​ ​ }

​ }

​ display(n);

​ degree(n);

​ return 0;

}
void display(int size)

​ int i,j;

​ printf("\n--------------------------------------------------------------------\n");

​ printf("\nAdjecency Matrix is:\n\n");

​ for(i=0;i<size;i++)

​ {

​ ​ for(j=0;j<size;j++)

​ ​ {

​ ​ ​ printf("%d\t",mat[i][j]);

​ ​ }

​ ​ printf("\n");

​ }

void degree(int n)

​ int i,j,indegree=0,outdegree=0;

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

​ {

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

​ ​ ​ {

​ ​ ​ ​ if (mat[i][j]==1)

​ ​ ​ ​ ​ outdegree++;

​ ​ ​ ​ if (mat[j][i]==1)

​ ​ ​ ​ ​ indegree++;

​ ​ ​ }
​ ​ ​ printf("\nIndegree, Outdegree and Total Degree of vertex %d is %d, %d,
%d",i+1,indegree,outdegree,indegree+outdegree);​

​ ​ ​ indegree=0;

​ ​ ​ outdegree=0;

​ } // for

​ printf("\n\n");

Set B

a) Write a C program that accepts the vertices and edges of a graph and store it as an
adjacency matrix. Implement function to traverse the graph using Breadth First Search
(BFS) traversal.

//adjacency matrix BFS

#include<stdio.h>

#include<stdlib.h>

#define MAX 100

#define initial 1

#define waiting 2

#define visited 3

int n;

int mat[MAX][MAX];

int state[MAX];

void accept();

void BF_Traversal();

void BFS(int v);


int queue[MAX], front = -1,rear = -1;

void insert_queue(int vertex);

int delete_queue();

int isEmpty_queue();

int main()

​ accept();

​ BF_Traversal();

​ return 0;

void accept()

​ int i, j;

​ char reply;

​ printf("How many vertices:");

​ scanf("%d",&n);

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

​ {

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

​ {

​ ​ printf("\n Is there edge between %d & %d ? (Y/N/y/n) :",i,j);

​ ​ scanf(" %c", &reply);

​ ​ if ( reply == 'y' || reply == 'Y' )

​ ​ mat[i][j] = 1;

​ ​ else
​ ​ mat[i][j] = 0;

​ ​ }

​ }

void BF_Traversal()

​ int v;

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

​ ​ state[v] = initial;

​ printf("\nEnter Start Vertex for BFS: ");

​ scanf("%d", &v);

​ printf("\nBFS Traversal is: ");

​ BFS(v);

​ printf("\n\n");

void BFS(int v)

​ int i;

​ insert_queue(v);

​ state[v] = waiting;


​ while(!isEmpty_queue())

​ {

​ ​ v = delete_queue( );

​ ​ printf("%d ",v);

​ ​ state[v] = visited;

​ ​

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

​ ​ {

​ ​ ​ if(mat[v][i] == 1 && state[i] == initial)

​ ​ ​ {

​ ​ ​ ​ insert_queue(i);

​ ​ ​ ​ state[i] = waiting;

​ ​ ​ }

​ ​ }

​ }

​ printf("\n");

void insert_queue(int vertex)

​ if(front == -1)

​ ​ front = 0;

​ rear = rear+1;

​ queue[rear] = vertex ;

int isEmpty_queue()
{

​ if(front == -1 || front > rear)

​ ​ return 1;

​ else

​ ​ return 0;

int delete_queue()

​ int delete_item;

​ delete_item = queue[front];

​ front = front+1;

​ return delete_item;

b) Write a C program that accepts the vertices and edges of a graph and store it as an
adjacency matrix. Implement function to traverse the graph using Depth First Search
(DFS) traversal.

//adjacency matrix DFS

#include<stdio.h>

void DFS(int);

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

void main()

​ int i,j,v;

​ char reply;
​ printf("How many vertices:");

​ scanf("%d",&n);

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

​ {

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

​ {

​ ​ printf("\nIs there edge between %d & %d ? (Y/N/y/n) :",i,j);

​ ​ scanf(" %c", &reply);

​ ​ if ( reply == 'y' || reply == 'Y' )

​ ​ mat[i][j] = 1;

​ ​ else

​ ​ mat[i][j] = 0;

​ ​ }

​ }

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

​ visited[i]=0;

​ printf("\nEnter the start vertex: ");

​ scanf("%d",&v);

​ printf("\nDFS Traversal is:");

​ DFS(v);

​ printf("\n\n");

void DFS(int i)

{
​ int j;

​ printf("%d ",i);

​ visited[i]=1;

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

​ if(!visited[j] && mat[i][j]==1)

​ ​ DFS(j);

Assignment 4: Graph as Adjacency List

Set A

a) Write a C program that accepts the vertices and edges of a graph. Create adjacency list
and display the adjacency list.

//read graph as adjacency list and print it.

#include<stdio.h>

#include<stdlib.h>

typedef struct node

int vertex;

struct node *next;

}node;

//heads of linked list

node *ll[20];

int n;
//create adjacency list

void read_graph();

//insert an edge (vi,vj) in te adjacency list

void insert(int,int);

//print adjacency list

void printlist();

void main()

read_graph();

printf("\nAdjacency List is:\n");

printlist();

printf("\n");

void read_graph()

​ int i,vi,vj,no_of_edges;

​ printf("\nEnter number of vertices:");

​ scanf("%d",&n);//n=6

​ //initialise ll[] with a null

​ ll[0]=NULL;

​ //read edges and insert them in G[]

​ printf("\nEnter number of edges:");

​ scanf("%d",&no_of_edges);
​ for(i=0;i<no_of_edges;i++)

​ {

​ ​ printf("Enter an edge(initial_vertex end_vertex):");

​ ​ scanf("%d%d",&vi,&vj);

​ ​ insert(vi,vj);

​ }

void insert(int vi,int vj)

node *p,*q;

q=(node*)malloc(sizeof(node));

q->vertex=vj;

q->next=NULL;

//insert the node in the linked list number vi

if(ll[vi]==NULL)

ll[vi]=q;

else

//go to end of the linked list

p=ll[vi];

​ ​ while(p->next!=NULL)

​ ​ p=p->next;

​ p->next=q;
}

}//insert()

void printlist()

​ struct node *p;​

​ int i;

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

​ {

​ ​ ​ printf("\n%d=",i);

​ ​ ​ p=ll[i];

​ ​ ​ while(p!=NULL)

​ ​ ​ {

​ ​ ​ ​ printf("%d->",p->vertex);

​ ​ ​ ​ p=p->next;

​ ​ ​ }

​ ​ ​ printf("NULL\n");​

​ } // for

b) Write a C program that accepts the vertices and edges of a graph. Create adjacency list.
Implement functions to print indegree, outdegree and total degree of all vertex of graph.

//read graph as adjacency list and find out indegree,outdegree

//and total degree of each node in graph.

#include<stdio.h>

#include<stdlib.h>

typedef struct node


{

struct node *next;

int vertex;

}node;

//heads of linked list

node *ll[20];

int n;

//create adjacency list

void read_graph();

//insert an edge (vi,vj) in the adjacency list

void insert(int,int);

void degree();

void main()

int i,v;

read_graph();

degree(n);

printf("\n\n");

void read_graph()

​ int i,vi,vj,no_of_edges;

​ printf("\nEnter number of vertices:");

​ scanf("%d",&n);
​ //initialise ll[] with a null

​ ll[0]=NULL;

​ //read edges and insert them in G[]

​ printf("\nEnter number of edges:");

​ scanf("%d",&no_of_edges);

​ for(i=0;i<no_of_edges;i++)

​ {

​ ​ printf("Enter an edge(u v):");

​ ​ scanf("%d%d",&vi,&vj);

​ ​ insert(vi,vj);

​ }

void insert(int vi,int vj)

node *p,*q;

//acquire memory for the new node

q=(node*)malloc(sizeof(node));

q->vertex=vj;

q->next=NULL;

//insert the node in the linked list number vi

if(ll[vi]==NULL)
ll[vi]=q;

else

//go to end of the linked list

p=ll[vi];

​ ​ while(p->next!=NULL)

​ ​ p=p->next;

​ p->next=q;

void degree(int n)

​ int i,indegree[10],outdegree[10];

​ struct node *p;​

​ for(i=0;i<10;i++)indegree[i]=0;

​ for(i=0;i<10;i++)outdegree[i]=0;

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

​ {

​ ​ ​ p=ll[i];

​ ​ ​ while(p!=NULL)

​ ​ ​ {

​ ​ ​ ​ indegree[p->vertex]+=1;

​ ​ ​ ​ outdegree[i]+=1;

​ ​ ​ ​ p=p->next;

​ ​ ​ }
​ } // for

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

​ ​ printf("\nIndegree, Outdegree and Total Degree of vertex %d is %d, %d,


%d",i,indegree[i],outdegree[i],indegree[i]+outdegree[i]);

Set B

a) Write a C program that accepts the vertices and edges of a graph and store it as an
adjacency list. Implement function to traverse the graph using Breadth First Search (BFS)
traversal.

// Adjacency list BFS

#include <stdio.h>

#include <stdlib.h>

#define SIZE 40

struct queue {

int items[SIZE];

int front;

int rear;

};

struct queue* createQueue();

void enqueue(struct queue* q, int);

int dequeue(struct queue* q);

void display(struct queue* q);

int isEmpty(struct queue* q);

void printQueue(struct queue* q);


struct node {

int vertex;

struct node* next;

};

struct node* createNode(int);

struct Graph {

int numVertices;

struct node** adjLists;

int* visited;

};

// BFS algorithm

void bfs(struct Graph* graph, int startVertex) {

struct queue* q = createQueue();

graph->visited[startVertex] = 1;

enqueue(q, startVertex);

while (!isEmpty(q)) {

printQueue(q);

int currentVertex = dequeue(q);

printf("Visited %d\n", currentVertex);

struct node* temp = graph->adjLists[currentVertex];


while (temp) {

int adjVertex = temp->vertex;

if (graph->visited[adjVertex] == 0) {

graph->visited[adjVertex] = 1;

enqueue(q, adjVertex);

temp = temp->next;

// Creating a node

struct node* createNode(int v) {

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

newNode->vertex = v;

newNode->next = NULL;

return newNode;

// Creating a graph

struct Graph* createGraph(int vertices) {

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

graph->numVertices = vertices;

graph->adjLists = malloc(vertices * sizeof(struct node*));

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


int i;

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

graph->adjLists[i] = NULL;

graph->visited[i] = 0;

return graph;

// Add edge

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

// Add edge from src to dest

struct node* newNode = createNode(dest);

newNode->next = graph->adjLists[src];

graph->adjLists[src] = newNode;

// Add edge from dest to src

newNode = createNode(src);

newNode->next = graph->adjLists[dest];

graph->adjLists[dest] = newNode;

// Create a queue

struct queue* createQueue() {

struct queue* q = malloc(sizeof(struct queue));

q->front = -1;
q->rear = -1;

return q;

// Check if the queue is empty

int isEmpty(struct queue* q) {

if (q->rear == -1)

return 1;

else

return 0;

// Adding elements into queue

void enqueue(struct queue* q, int value) {

if (q->rear == SIZE - 1)

printf("\nQueue is Full!!");

else {

if (q->front == -1)

q->front = 0;

q->rear++;

q->items[q->rear] = value;

// Removing elements from queue

int dequeue(struct queue* q) {

int item;
if (isEmpty(q)) {

printf("Queue is empty");

item = -1;

} else {

item = q->items[q->front];

q->front++;

if (q->front > q->rear) {

printf("Resetting queue ");

q->front = q->rear = -1;

return item;

// Print the queue

void printQueue(struct queue* q) {

int i = q->front;

if (isEmpty(q)) {

printf("Queue is empty");

} else {

printf("\nQueue contains \n");

for (i = q->front; i < q->rear + 1; i++) {

printf("%d ", q->items[i]);

}
int main() {

struct Graph* graph = createGraph(4);

addEdge(graph, 0, 1);

addEdge(graph, 0, 2);

addEdge(graph, 1, 2);

addEdge(graph, 2, 0);

addEdge(graph, 2, 3);

addEdge(graph, 3, 3);

//addEdge(graph, 3, 4);

bfs(graph, 2);

return 0;

b) Write a C program that accepts the vertices and edges of a graph and store it as an
adjacency list. Implement function to traverse the graph using Depth First Search (DFS)
traversal.

//adjacency list DFS

#include<stdio.h>

#include<stdlib.h>

typedef struct node

struct node *next;

int vertex;

}node;
node *ll[20];

//heads of linked list

int visited[20];

int n;

void read_graph();

//create adjacency list

void insert(int,int);

//insert an edge (vi,vj) in te adjacency list

void DFS(int);

void main()

int i,v;

read_graph();

//initialised visited to 0

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

visited[i]=0;

printf("\nEnter the start vertex:");

scanf("%d",&v);

printf("\nDFS Traversal is:");

DFS(v);

printf("\n\n");

void DFS(int i)

{
node *p;

printf("%d ",i);

p=ll[i];

visited[i]=1;

while(p!=NULL)

​ i=p->vertex;

​ if(!visited[i])

​ DFS(i);

p=p->next;

void read_graph()

​ int i,vi,vj,no_of_edges;

​ printf("\nEnter number of vertices:");

​ scanf("%d",&n);

​ //initialise G[] with a null

​ ll[0]=NULL;

​ //read edges and insert them in G[]

​ printf("\nEnter number of edges:");

​ scanf("%d",&no_of_edges);
​ for(i=0;i<no_of_edges;i++)

​ {

​ ​ printf("Enter an edge(u,v):");

​ ​ scanf("%d%d",&vi,&vj);

​ ​ insert(vi,vj);

​ }

void insert(int vi,int vj)

node *p,*q;

//acquire memory for the new node

q=(node*)malloc(sizeof(node));

q->vertex=vj;

q->next=NULL;

//insert the node in the linked list number vi

if(ll[vi]==NULL)

ll[vi]=q;

else

//go to end of the linked list

p=ll[vi];

​ ​ while(p->next!=NULL)
​ ​ p=p->next;

​ p->next=q;

Assignment 5: Graph Applications – I


Set A
a) Write a C program for the implementation of Topological sorting.
//C program to Obtain the topological ordering of vertices in a given digraph
#include<stdio.h>
#include<conio.h>
#include<dos.h>
#include<time.h>
int a[10][10],n,indegree[10];
void find_indegree()
{
int i,j,sum;
for(j=0;j<n;j++)
{
sum=0;
for(i=0;i<n;i++)
sum+=a[i][j];
indegree[j]=sum;
}
}
void topology()
{
int i,u,v,t[10],s[10],top=-1,k=0;
delay(1000);
find_indegree();
for(i=0;i<n;i++)
{
if(indegree[i]==0)s[++top]=i;
}
while(top!=-1)
{
u=s[top--];
t[k++]=u;
for(v=0;v<n;v++)
{
if(a[u][v]==1)
{
indegree[v]--;
if(indegree[v]==0)s[++top]=v;
}
}
}
printf("The topological sequence is:");
for(i=0;i<n;i++)
printf("\t%d",t[i]+1);
}
void main()
{
int i,j;
clrscr();
printf("Enter the no ofjobs: ");
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]);
}
topology();
getch();
}
b) Write a C program for the Implementation of Prim’s Minimum spanning tree
algorithm.
//Prims algorithm
#include<stdio.h>
int a,b,u,v,n,i,j,ne=1;
int visited[10]={0},min,mincost=0,cost[10][10];
void main()
{
​ printf("\nEnter the number of nodes:");
​ scanf("%d",&n);
​ printf("\nEnter the adjacency matrix:\n");
​ for(i=1;i<=n;i++)
​ {
​ ​ for(j=1;j<=n;j++)
​ ​ {
​ ​ ​ scanf("%d",&cost[i][j]);
​ ​ ​ if(cost[i][j]==0)
​ ​ ​ ​ cost[i][j]=999;
​ ​ }
​ }

​ visited[1]=1;
​ printf("\n");
​ while(ne < n)
​ {
​ ​ for(i=1,min=999;i<=n;i++)
​ ​ {
​ ​ for(j=1;j<=n;j++)
​ ​ {
​ ​ if(cost[i][j]< min)
​ ​ {
​ ​ if(visited[i]!=0)
​ ​ {
​ ​ ​ min=cost[i][j];
​ ​ ​ a=u=i;
​ ​ ​ b=v=j;
​ ​ }
​ ​ if(visited[u]==0 || visited[v]==0)
​ ​ {
​ ​ ​ printf("\n Edge %d:(%d %d) cost:%d",ne++,a,b,min);
​ ​ ​ mincost+=min;
​ ​ ​ visited[b]=1;
​ ​ }
​ ​ cost[a][b]=cost[b][a]=999;
​ ​ }
​ ​ }
​ ​ }
​ }
​ printf("\n Minimun cost=%d\n\n",mincost);
}
Set B
a) Write a C program for the Implementation of Kruskal’s Minimum spanning
tree algorithm
//Kruskal's algorithm
#include<stdio.h>
#include<stdlib.h>
int i,j,k,a,b,u,v,n,ne=1;
int min,mincost=0,cost[9][9],parent[9];
int find(int);
int uni(int,int);
void main()
{
​ printf("\n\tImplementation of Kruskal's algorithm\n");
​ printf("\nEnter the no. of vertices:");
​ scanf("%d",&n);
​ printf("\nEnter the cost adjacency matrix:\n");
​ for(i=1;i<=n;i++)
​ {
​ ​ for(j=1;j<=n;j++)
​ ​ {
​ ​ ​ scanf("%d",&cost[i][j]);
​ ​ ​ if(cost[i][j]==0)
​ ​ ​ ​ cost[i][j]=999;
​ ​ }
​ }
​ printf("The edges of Minimum Cost Spanning Tree are\n");
​ while(ne < n)
​ {
​ ​ for(i=1,min=999;i<=n;i++)
​ ​ {
​ ​ ​ for(j=1;j <= n;j++)
​ ​ ​ {
​ ​ ​ ​ if(cost[i][j] < min)
​ ​ ​ ​ {
​ ​ ​ ​ ​ min=cost[i][j];
​ ​ ​ ​ ​ a=u=i;
​ ​ ​ ​ ​ b=v=j;
​ ​ ​ ​ }
​ ​ ​ }
​ ​ }
​ ​ u=find(u);
​ ​ v=find(v);
​ ​ if(uni(u,v))
​ ​ {
​ ​ ​ printf("%d edge (%d,%d) =%d\n",ne++,a,b,min);
​ ​ ​ mincost +=min;
​ ​ }
​ ​ cost[a][b]=cost[b][a]=999;
​ }
​ printf("\n\tMinimum cost = %d\n",mincost);
}
int find(int i)
{
​ while(parent[i])
​ i=parent[i];
​ return i;
}
int uni(int i,int j)
{
​ if(i!=j)
​ {
​ ​ parent[j]=i;
​ ​ return 1;
​ }
​ return 0;
}

Assignment 6: Graph Applications – II

Set A
a) Write a C program for the implementation of Dijkstra’s shortest path algorithm for
finding shortest path from a given source vertex using adjacency cost matrix.
#include<stdio.h>
#include<conio.h>
#define INFINITY 9999
#define MAX 10

void dijikstra(int G[MAX][MAX], int n, int startnode);

void main(){
​ int G[MAX][MAX], i, j, n, u;
​ clrscr();
​ printf("\nEnter the no. of vertices:: ");
​ scanf("%d", &n);
​ printf("\nEnter the adjacency matrix::\n");
​ for(i=0;i < n;i++)
​ ​ for(j=0;j < n;j++)
​ ​ ​ scanf("%d", &G[i][j]);
​ printf("\nEnter the starting node:: ");
​ scanf("%d", &u);
​ dijikstra(G,n,u);
​ getch();
}

void dijikstra(int G[MAX][MAX], int n, int startnode)


{
​ int cost[MAX][MAX], distance[MAX], pred[MAX];
​ int visited[MAX], count, mindistance, nextnode, i,j;
​ for(i=0;i < n;i++)
​ ​ for(j=0;j < n;j++)
​ ​ ​ if(G[i][j]==0)
​ ​ ​ ​ cost[i][j]=INFINITY;
​ ​ ​ else
​ ​ ​ ​ cost[i][j]=G[i][j];

​ for(i=0;i< n;i++)
​ {
​ ​ distance[i]=cost[startnode][i];
​ ​ pred[i]=startnode;
​ ​ visited[i]=0;
​ }
​ distance[startnode]=0;
​ visited[startnode]=1;
​ count=1;
​ while(count < n-1){
​ ​ mindistance=INFINITY;
​ ​ for(i=0;i < n;i++)
​ ​ ​ if(distance[i] < mindistance&&!visited[i])
​ ​ ​ {
​ ​ ​ ​ mindistance=distance[i];
​ ​ ​ ​ nextnode=i;
​ ​ ​ }
​ ​ visited[nextnode]=1;
​ ​ for(i=0;i < n;i++)
​ ​ ​ if(!visited[i])
​ ​ ​ ​ if(mindistance+cost[nextnode][i] < distance[i])
​ ​ ​ ​ {
​ ​ ​ ​ ​ distance[i]=mindistance+cost[nextnode][i];
​ ​ ​ ​ ​ pred[i]=nextnode;
​ ​ ​ ​ }
​ ​ ​ count++;
​ }

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


​ ​ if(i!=startnode)
​ ​ {
​ ​ ​ printf("\nDistance of %d = %d", i, distance[i]);
​ ​ ​ printf("\nPath = %d", i);
​ ​ ​ j=i;
​ ​ ​ do
​ ​ ​ {
​ ​ ​ ​ j=pred[j];
​ ​ ​ ​ printf(" <-%d", j);
​ ​ ​ }
​ ​ ​ while(j!=startnode);
​ ​ }
}

Set B
a) Write a C program for the implementation of Floyd Warshall’s algorithm for finding all
pairs shortest path using adjacency cost matrix.
#include<stdio.h>
int i, j, k,n,dist[10][10];
void floydWarshell ()
{
for (k = 0; k < n; k++)
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
if (dist[i][k] + dist[k][j] < dist[i][j])
dist[i][j] = dist[i][k] + dist[k][j];
}
int main()
{
int i,j;
printf("enter no of vertices :");
scanf("%d",&n);
printf("\n");
for(i=0;i<n;i++)
for(j=0;j<n;j++)
{
printf("dist[%d][%d]:",i,j);
scanf("%d",&dist[i][j]);
}
floydWarshell();
printf (" \n\n shortest distances between every pair of vertices \n");
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
printf ("%d\t", dist[i][j]);
printf("\n");
}
return 0;
}
Assignment 7: Hash Table-I
Set A
a) Write a program to implement various types of hash functions which are used
to place the data in a hash table
a. Division Method
b. Mid Square Method
c. Digit Folding Method
Accept n values from the user and display appropriate message in case of
collision for each of the above functions.

Set B
a) Write a menu driven program to implement hash table using array (insert,
search, delete, display). Use any of the above-mentioned hash functions. In case
of collision apply linear probing.

b) Write a menu driven program to implement hash table using array (insert,
search, delete, display). Use any of the above-mentioned hash functions. In case
of collision apply quadratic probing.

Assignment 8: Hash Table-II

Set A
a) Implement hash table using singly linked lists. Write a menu driven program to
perform operations on the hash table (insert, search, delete, display). Select appropriate
hashing function. In case of collision, use separate chaining.

#include<stdio.h>

#define size 7

int arr[size];
void init()
{
int i;
for(i = 0; i < size; i++)
arr[i] = -1;
}

void insert(int value)


{
int key = value % size;

if(arr[key] == -1)
{
arr[key] = value;
printf("%d inserted at arr[%d]\n", value,key);
}
else
{
printf("Collision : arr[%d] has element %d already!\n",key,arr[key]);
printf("Unable to insert %d\n",value);
}
}

void del(int value)


{
int key = value % size;
if(arr[key] == value)
arr[key] = -1;
else
printf("%d not present in the hash table\n",value);
}

void search(int value)


{
int key = value % size;
if(arr[key] == value)
printf("Search Found\n");
else
printf("Search Not Found\n");
}

void print()
{
int i;
for(i = 0; i < size; i++)
printf("arr[%d] = %d\n",i,arr[i]);
}

int main()
{
init();
insert(10); //key = 10 % 7 ==> 3
insert(4); //key = 4 % 7 ==> 4
insert(2); //key = 2 % 7 ==> 2
insert(3); //key = 3 % 7 ==> 3 (collision)

printf("Hash table\n");
print();
printf("\n");

printf("Deleting value 10..\n");


del(10);
printf("After the deletion hash table\n");
print();
printf("\n");

printf("Deleting value 5..\n");


del(5);
printf("After the deletion hash table\n");
print();
printf("\n");

printf("Searching value 4..\n");


search(4);
printf("Searching value 10..\n");
search(10);

return 0;
}
Set B

a) Implement hash table using doubly linked lists. Write a menu driven program to perform
operations on the hash table (insert, search, delete, display). Select appropriate hashing function.
In case of collision, use separate chaining.

You might also like