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

Daa Lab Programs

The document contains implementations of various algorithms including BFS, DFS, Merge Sort, Quick Sort, Knapsack (using brute force, greedy, and dynamic programming methods), Kruskal's and Prim's algorithms for finding minimum spanning trees, and Dijkstra's algorithm for shortest paths. Each algorithm is presented with C code examples demonstrating their functionality. The document serves as a comprehensive guide for understanding and implementing these fundamental algorithms in programming.

Uploaded by

cobrastealth04
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)
5 views

Daa Lab Programs

The document contains implementations of various algorithms including BFS, DFS, Merge Sort, Quick Sort, Knapsack (using brute force, greedy, and dynamic programming methods), Kruskal's and Prim's algorithms for finding minimum spanning trees, and Dijkstra's algorithm for shortest paths. Each algorithm is presented with C code examples demonstrating their functionality. The document serves as a comprehensive guide for understanding and implementing these fundamental algorithms in programming.

Uploaded by

cobrastealth04
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/ 21

DAA LAB PROGRAMS

1. BFS and DFS

//Implementation of BFS
#include<stdio.h>
int cost[10][10],i,j,k,n,m,queue[10],front,rear,v;
int visited[10];
void BFS()
{
printf("enter the initial vertex");
scanf("%d",&v);
printf("visited vertices\n");
visited[v]=1;
queue[++rear]=v;
while(front!=rear)
{
v=queue[++front];
printf("%d",v);
for(j=1;j<=n;j++)
if(!visited[j]&& cost[v][j]==1)
{
queue[++rear]=j;
visited[j]=1;
}
}
}
int main()
{
printf("enter the no of vertices");
scanf("%d",&n);
printf("enter the no of edges");
scanf("%d",&m);
front=-1;rear=-1;
for ( int i=1;i<=10;i++) visited[i]=0;
for (int i=0;i<10;i++)
for(j=0;j<10;j++)
cost[i][j]=0;
printf("\nEnter EDGES");
for(k=1;k<=m;k++)
{
scanf("%d%d",&i,&j);
cost[i][j]=1;
cost[j][i]=1;
}
BFS();
}
//Implementation of DFS

#include<stdio.h>
int cost[10][10],i,j,k,n,m,stack[10],top=-1,v;
int visited[10];
void DFS()
{
printf("enter the initial vertex");
scanf("%d",&v);
printf("visited vertices\n");
stack[++top]=v;
while(top!=-1)
{
v=stack[top--];
if(visited[v]==0)
{
printf("%d",v);
visited[v]=1;
}
else
continue;
for(j=n;j>=1;j--)
if(!visited[j]&& cost[v][j]==1)
stack[++top]=j;
}
}
int main()
{
printf("enter the no of vertices");
scanf("%d",&n);
printf("enter the no of edges");
scanf("%d",&m);
for ( int i=1;i<=10;i++)
{
visited[i]=0;
}
for (int i=0;i<10;i++)
for(j=0;j<10;j++)
cost[i][j]=0;
printf("\nEnter EDGES");
for(k=1;k<=m;k++)
{
scanf("%d%d",&i,&j);
cost[i][j]=1;
cost[j][i]=1;
}
DFS();
}
1. Merge sort and Quick sort

//Merge Sort
#include<stdio.h>
#include <stdio.h>
#include <time.h>

void mergesort(int a[],int lb,int mid, int ub)


{
int i=lb,j=mid+1,k=0,b[50];
while(i<=mid&&j<=ub)
{
if(a[i]<a[j])
{
b[k++]=a[i++];
}
else
{
b[k++]=a[j++];
}
}
while(i<=mid)
{
b[k++]=a[i++];
}
while(j<=ub)
{
b[k++]=a[j++];
}
for(k=0;k<=ub-lb;k++)
{
a[k+lb]=b[k];
}
}

void merge(int a[],int low,int high)


{
int mid;
if(low<high)
{
mid=(low+high)/2;
merge(a,low,mid);
merge(a,mid+1,high);
mergesort(a,low,mid,high);
}
}
int main()
{
int count=0;
clock_t t;
int i, a[30],n;
printf("Enter the number of elements: ");
scanf("%d",&n);
printf("Enter elements:\n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("\n\nBefore sorting:");
for(i=0;i<n;i++)
{
printf("%d ",a[i]);
}
t=clock();
merge(a,0,n-1);
t=clock()-t;
double tt=((double)t)/CLOCKS_PER_SEC;
printf("\n\nAfter sorting:");
for(i=0;i<n;i++)
{
printf("%d ",a[i]);

}
printf("time taken:%f sec",tt);

//Quick Sort
#include<stdio.h>
void QuickSort(int [],int,int);
int main()
{
int count=0;
clock_t t;
int i, n, list[20];
printf("enter range of elements");
scanf("%d",&n);
printf("enter elements\n");
for(i=0;i<n; i++)
{
scanf("%d",&list[i]);
}
t=clock();
QuickSort(list,0,n-1);
t=clock()-t;
double tt=((double)t)/CLOCKS_PER_SEC;
printf("after sorting: ");
for(i=0; i<n; i++)
{
printf("%d ",list[i]);
}
printf("time taken:%f sec",tt);
}

void QuickSort(int list[],int first,int last)


{
int pivot,i,j,temp;
if(first < last)
{
pivot = first;
i = first;
j = last;
while(i < j)
{
while(list[i] <= list[pivot] && i < last)
i++;
while(list[j] > list[pivot])
j--;
if(i < j)
{
temp = list[i];
list[i] = list[j];
list[j] = temp;
}
}
temp = list[pivot];
list[pivot] = list[j];
list[j] = temp;
QuickSort(list,first,j-1);
QuickSort(list,j+1,last);
}
}

2. Knapsack

//brute force

// maximum of two integers


int max(int a, int b) { return (a > b) ? a : b; }

// Returns the maximum value that can be


// put in a knapsack of capacity W
int knapSack(int W, int wt[], int val[], int n)
{
// Base Case
if (n == 0 || W == 0)
return 0;

// If weight of the nth item is more than


// Knapsack capacity W, then this item cannot
// be included in the optimal solution
if (wt[n - 1] > W)
return knapSack(W, wt, val, n - 1);

// Return the maximum of two cases:


// (1) nth item included
// (2) not included
else
return max(
val[n - 1]
+ knapSack(W - wt[n - 1], wt, val, n - 1),
knapSack(W, wt, val, n - 1));
}

// Driver code
int main()
{
int profit[] = { 60, 100, 120 };
int weight[] = { 10, 20, 30 };
int W = 50;
int n = sizeof(profit) / sizeof(profit[0]);
printf("%d", knapSack(W, weight, profit, n));
return 0;
}

//Greedy method

#include <stdio.h>
int n = 5;
int p[10] = {3, 3, 2, 5, 1};
int w[10] = {10, 15, 10, 12, 8};
int W = 10;
int main(){
int cur_w;
float tot_v;
int i, maxi;
int used[10];
for (i = 0; i< n; ++i)
used[i] = 0;
cur_w = W;
while (cur_w> 0) {
maxi = -1;
for (i = 0; i< n; ++i)
if ((used[i] == 0) &&((maxi == -1) || ((float)w[i]/p[i] > (float)w[maxi]/p[maxi])))
maxi = i;
used[maxi] = 1;
cur_w -= p[maxi];
tot_v += w[maxi];
if (cur_w>= 0)
printf("Added object %d (%d, %d) completely in the bag. Space left: %d.\n", maxi + 1,
w[maxi],p[maxi], cur_w);
else {
printf("Added %d%% (%d, %d) of object %d in the bag.\n", (int)((1 + (float)cur_w/p[maxi]) *
100),w[maxi], p[maxi], maxi + 1);
tot_v -= w[maxi];
tot_v += (1 + (float)cur_w/p[maxi]) * w[maxi];
}
}
printf("Filled the bag with objects worth %.2f.\n", tot_v);
return 0;
}

//Dynamic programming

#include <stdio.h>
#include <string.h>
int findMax(int n1, int n2){
if(n1>n2) {
return n1;
} else {
return n2;
}
}
int knapsack(int W, int wt[], int val[], int n){
int K[n+1][W+1];
for(int i = 0; i<=n; i++) {
for(int w = 0; w<=W; w++) {
if(i == 0 || w == 0) {
K[i][w] = 0;
} else if(wt[i-1] <= w) {
K[i][w] = findMax(val[i-1] + K[i-1][w-wt[i-1]], K[i-1][w]);
} else {
K[i][w] = K[i-1][w];
}
}
}
return K[n][W];
}
int main(){
int val[5] = {70, 20, 50};
int wt[5] = {11, 12, 13};
int W = 30;
int len = sizeof val / sizeof val[0];
printf("Maximum Profit achieved with this knapsack: %d", knapsack(W, wt, val, len));
}

3. Krushkals and prims

//Krushkals

#include <stdio.h>

#include <stdlib.h>
// Comparator function to use in sorting
int comparator(const void* p1, const void* p2)
{
const int(*x)[3] = p1;
const int(*y)[3] = p2;

return (*x)[2] - (*y)[2];


}

// Initialization of parent[] and rank[] arrays


void makeSet(int parent[], int rank[], int n)
{
for (int i = 0; i< n; i++) {
parent[i] = i;
rank[i] = 0;
}
}
// Function to find the parent of a node
int findParent(int parent[], int component)
{
if (parent[component] == component)
return component;
return parent[component]
= findParent(parent, parent[component]);
}

// Function to unite two sets


void unionSet(int u, int v, int parent[], int rank[], int n)
{
// Finding the parents
u = findParent(parent, u);
v = findParent(parent, v);
if (rank[u] < rank[v]) {
parent[u] = v;
}
else if (rank[u] > rank[v]) {
parent[v] = u;
}
else {
parent[v] = u;
// Since the rank increases if
// the ranks of two sets are same
rank[u]++;
}
}
// Function to find the MST
void kruskalAlgo(int n, int edge[n][3])
{
// First we sort the edge array in ascending order
// so that we can access minimum distances/cost
qsort(edge, n, sizeof(edge[0]), comparator);
int parent[n];
int rank[n];
// Function to initialize parent[] and rank[]
makeSet(parent, rank, n);
// To store the minimun cost
int minCost = 0;
printf( "Following are the edges in the constructed MST\n");
for (int i = 0; i< n; i++) {
int v1 = findParent(parent, edge[i][0]);
int v2 = findParent(parent, edge[i][1]);
int wt = edge[i][2];

// If the parents are different that


// means they are in different sets so
// union them
if (v1 != v2) {
unionSet(v1, v2, parent, rank, n);
minCost += wt;
printf("%d -- %d == %d\n", edge[i][0],
edge[i][1], wt);
}
}
printf("Minimum Cost Spanning Tree: %d\n", minCost);
}
// Driver code
int main()
{

int edge[5][3] = { { 0, 1, 10 },
{ 0, 2, 6 },
{ 0, 3, 5 },
{ 1, 3, 15 },
{ 2, 3, 4 } };
kruskalAlgo(5, edge);
return 0;
}

//Prims

#include<stdio.h>
#include<stdlib.h>
#define inf 99999
#define MAX 10
int G[MAX][MAX] = {
{0, 19, 8},
{21, 0, 13},
{15, 18, 0}
};
int S[MAX][MAX], n;
int prims();
int main(){
int i, j, cost;
n = 3;
cost=prims();
printf("\nSpanning tree:\n");
for(i=0; i<n; i++) {
printf("\n");
for(j=0; j<n; j++)
printf("%d\t",S[i][j]);
}
printf("\n\nMinimum cost = %d", cost);
return 0;
}
int prims(){
int C[MAX][MAX];
int u, v, min_dist, dist[MAX], from[MAX];
int visited[MAX],ne,i,min_cost,j;
//create cost[][] matrix,spanning[][]
for(i=0; i<n; i++)
for(j=0; j<n; j++) {
if(G[i][j]==0)
C[i][j]=inf;
else
C[i][j]=G[i][j];
S[i][j]=0;
}
//initialise visited[],distance[] and from[]
dist[0]=0;
visited[0]=1;
for(i=1; i<n; i++) {
dist[i] = C[0][i];
from[i] = 0;
visited[i] = 0;
}
min_cost = 0; //cost of spanning tree
ne = n-1; //no. of edges to be added
while(ne > 0) {
//find the vertex at minimum distance from the tree
min_dist = inf;
for(i=1; i<n; i++)
if(visited[i] == 0 &&dist[i] <min_dist) {
v = i;
min_dist = dist[i];
}
u = from[v];

//insert the edge in spanning tree


S[u][v] = dist[v];
S[v][u] = dist[v];
ne--;
visited[v]=1;
//updated the distance[] array
for(i=1; i<n; i++)
if(visited[i] == 0 && C[i][v] <dist[i]) {
dist[i] = C[i][v];
from[i] = v;
}
min_cost = min_cost + C[u][v];
}
return(min_cost);
}
4. Dijkstra Algorithm

#include<stdio.h>
#include<limits.h>
#include<stdbool.h>
int min_dist(int[], bool[]);
void greedy_dijsktra(int[][6],int);
int min_dist(int dist[], bool visited[]){ // finding minimum dist
int minimum=INT_MAX,ind;
for(int k=0; k<6; k++) {
if(visited[k]==false && dist[k]<=minimum) {
minimum=dist[k];
ind=k;
}
}
return ind;
}
void greedy_dijsktra(int graph[6][6],int src){
int dist[6];
bool visited[6];
for(int k = 0; k<6; k++) {
dist[k] = INT_MAX;
visited[k] = false;
}
dist[src] = 0; // Source vertex dist is set 0
for(int k = 0; k<6; k++) {
int m=min_dist(dist,visited);
visited[m]=true;
for(int k = 0; k<6; k++) {
// updating the dist of neighbouring vertex
if(!visited[k] && graph[m][k] && dist[m]!=INT_MAX && dist[m]+graph[m][k]<dist[k])
dist[k]=dist[m]+graph[m][k];
}
}
printf("Vertex\t\tdist from source vertex\n");
for(int k = 0; k<6; k++) {
char str=65+k;
printf("%c\t\t\t%d\n", str, dist[k]);
}
}
int main(){
int graph[6][6]= {
{0, 1, 2, 0, 0, 0},
{1, 0, 0, 5, 1, 0},
{2, 0, 0, 2, 3, 0},
{0, 5, 2, 0, 2, 2},
{0, 1, 3, 2, 0, 1},
{0, 0, 0, 2, 1, 0}
};
greedy_dijsktra(graph,0);
return 0;
}

5. Travelling salesman

//Brute force

#include <stdio.h>
#include <limits.h>

#define NUM_CITIES 4

int graph[NUM_CITIES][NUM_CITIES] = {
{0, 10, 15, 20},
{10, 0, 35, 25},
{15, 35, 0, 30},
{20, 25, 30, 0}
};

int visited[NUM_CITIES];
int minCost = INT_MAX;

void tsp(int currentCity, int visitedCount, int costSoFar) {


if (visitedCount == NUM_CITIES && graph[currentCity][0] != 0) {
int totalCost = costSoFar + graph[currentCity][0];
if (totalCost < minCost) {
minCost = totalCost;
}
return;
}

for (int i = 0; i < NUM_CITIES; i++) {


if (!visited[i] && graph[currentCity][i] != 0) {
visited[i] = 1;
tsp(i, visitedCount + 1, costSoFar + graph[currentCity][i]);
visited[i] = 0;
}
}
}

int main() {
for (int i = 0; i < NUM_CITIES; i++) {
visited[i] = 0;
}
visited[0] = 1; // Starting from the first city
tsp(0, 1, 0); // Start from city 0, one city is already visited, cost is 0

printf("Minimum cost of the TSP: %d\n", minCost);

return 0;
}

//Dynamic

#include<stdio.h>
int ary[10][10],completed[10],n,cost=0;
void takeInput()
{
int i,j;
printf("Enter the number of villages: ");
scanf("%d",&n);
printf("\nEnter the Cost Matrix\n");

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


{
printf("\nEnter Elements of Row: %d\n",i+1);
for( j=0;j < n;j++)
scanf("%d",&ary[i][j]);
completed[i]=0;
}
printf("\n\nThe cost list is:");
for( i=0;i < n;i++)
{
printf("\n");
for(j=0;j < n;j++)
printf("\t%d",ary[i][j]);
}
}

void mincost(int city)


{
int i,ncity;
completed[city]=1;
printf("%d--->",city+1);
ncity=least(city);
if(ncity==999)
{
ncity=0;
printf("%d",ncity+1);
cost+=ary[city][ncity];
return;
}
mincost(ncity); }
int least(int c) {
int i,nc=999;
int min=999,kmin;
for(i=0;i < n;i++) {
if((ary[c][i]!=0)&&(completed[i]==0))
if(ary[c][i]+ary[i][c] < min) {
min=ary[i][0]+ary[c][i];
kmin=ary[c][i];
nc=i; }}
if(min!=999)
cost+=kmin;
return nc;
}
int main() {
takeInput();
printf("\n\nThe Path is:\n");
mincost(0); //passing 0 because starting vertex
printf("\n\nMinimum cost is %d\n ",cost);
return 0;
}

6. Floyds

#include<stdio.h>
int min(int,int);
void floyds(int p[10][10],int n){
int i,j,k;
for (k=1; k<=n; k++)
for (i=1; i<=n; i++)
for (j=1; j<=n; j++)
if(i==j)
p[i][j]=0;
else
p[i][j]=min(p[i][j],p[i][k]+p[k][j]);
}
int min(int a,int b){
if(a<b)
return(a);
else
return(b);
}
void main(){
int w,n,e,i,j;
n = 3;
e = 3;
int p[10][10];
for (i=1; i<=n; i++) {
for (j=1; j<=n; j++)
p[i][j]=999;
}
p[1][2] = 10;
p[2][3] = 15;
p[3][1] = 12;
printf("\n Matrix of input data:\n");
for (i=1; i<=n; i++) {
for (j=1; j<=n; j++)
printf("%d \t",p[i][j]);
printf("\n");
}
floyds(p,n);
printf("\n Transitive closure:\n");
for (i=1; i<=n; i++) {
for (j=1; j<=n; j++)
printf("%d \t",p[i][j]);
printf("\n");
}
printf("\n The shortest paths are:\n");
for (i=1; i<=n; i++)
for (j=1; j<=n; j++) {
if(i!=j)
printf("\n <%d,%d>=%d",i,j,p[i][j]);
}
}

7. N-queens, Hamiltonian, graph coloring

//N Queens

#include<stdio.h>
#include<math.h>
int board[20],count;
int main()
{
int n,i,j;
void queen(int row,int n);
printf(" - N Queens Problem Using Backtracking -");
printf("\n\nEnter number of Queens:");
scanf("%d",&n);
queen(1,n);
return 0;
}
//function for printing the solution
void print(int n)
{
int i,j;
printf("\n\nSolution %d:\n\n",++count);
for(i=1;i<=n;++i)
printf("\t%d",i);
for(i=1;i<=n;++i) {
printf("\n\n%d",i);
for(j=1;j<=n;++j) //for nxn board
{
if(board[i]==j)
printf("
\tQ"); //queen at i,j position
else
printf("\t-"); //empty slot
}
}}
/*funtion to check conflicts
If no conflict for desired postion returns 1 otherwise returns 0*/
int place(int row,int column) {
int i;
for(i=1;i<=row-1;++i)
{
//checking column and digonal conflicts
if(board[i]==column)
return 0;
else
if(abs(board[i]-column)==abs(i-row))
return 0;
}
return 1; //no conflicts
}
//function to check for proper positioning of queen
void queen(int row,int n) {
int column;
for(column=1;column<=n;++column) {
if(place(row,column))
{
board[row]=column; //no conflicts so place queen
if(row==n) //dead end
print(n); //printing the board configuration
else //try queen with next position
queen(row+1,n);
}
}}

//Hamiltonian
#include <stdio.h>
#define NODE 5
int graph[NODE][NODE] = {
{0, 1, 0, 1, 0},
{1, 0, 1, 1, 1},
{0, 1, 0, 0, 1},
{1, 1, 0, 0, 1},
{0, 1, 1, 1, 0},
};
int path[NODE];
// Function to display the Hamiltonian cycle
void displayCycle() {
printf("Cycle Found: ");
for (int i = 0; i < NODE; i++)
printf("%d ", path[i]);
// Print the first vertex again
printf("%d\n", path[0]);
}
// Function to check if adding vertex v to the path is valid
int isValid(int v, int k) {
// If there is no edge between path[k-1] and v
if (graph[path[k - 1]][v] == 0)
return 0;
// Check if vertex v is already taken in the path
for (int i = 0; i < k; i++)
if (path[i] == v)
return 0;
return 1;
}
// Function to find the Hamiltonian cycle
int cycleFound(int k) {
// When all vertices are in the path
if (k == NODE) {
// Check if there is an edge between the last and first vertex
if (graph[path[k - 1]][path[0]] == 1)
return 1;
else
return 0;
}
// Try adding each vertex (except the starting point) to the path
for (int v = 1; v < NODE; v++) {
if (isValid(v, k)) {
path[k] = v;
if (cycleFound(k + 1) == 1)
return 1;
// Backtrack: Remove v from the path
path[k] = -1;
}
}
return 0;
}
// Function to find and display the Hamiltonian cycle
int hamiltonianCycle() {
for (int i = 0; i < NODE; i++)
path[i] = -1;
// Set the first vertex as 0
path[0] = 0;
if (cycleFound(1) == 0) {
printf("Solution does not exist\n");
return 0;
}
displayCycle();
return 1;
}
int main() {
hamiltonianCycle();
return 0;
}
//Graph Coloring

#include<stdio.h>
static int m, n;
static int c=0;
static int count=0;
int g[50][50];
int x[50];
void nextValue(int k);
void GraphColoring(int k);
void main() {
int i, j;
int temp;
printf("\nEnter the number of nodes: " );
scanf("%d", &n);
printf("\nEnter Adjacency Matrix:\n");

for(i=1;i<=n;i++) {
for(j=1;j<=n;j++)
{
scanf("%d", &g[i][j]);
}}
printf("\nPossible Solutions are\n");
for(m=1;m<=n;m++) {
if(c==1)
{
break;
}
GraphColoring(1); }
printf("\nThe chromatic number is %d", m-1);

//in for loop, m gets incremented first and then the condition is checked
//so it is m minus 1
printf("\nThe total number of solutions is %d", count);
}
void GraphColoring(int k) {
int i;
while(1) {
nextValue(k);
if(x[k]==0)
{
return;
}
if(k==n) {
c=1;
for(i=1;i<=n;i++)
{
printf("%d ", x[i]);

}
count++;
printf("\n");
}
else
GraphColoring(k+1);
}
}
void nextValue(int k)
{
int j;
while(1)
{
x[k]=(x[k]+1)%(m+1);
if(x[k]==0)
{
return;
}
for(j=1;j<=n;j++)
{
if(g[k][j]==1&&x[k]==x[j])
break;
}
if(j==(n+1))
{
return;
}
}
}

You might also like