0% found this document useful (0 votes)
44 views32 pages

ADA Lab Manual

This lab manual outlines a series of programming experiments focused on algorithm design and implementation using C/C++. It includes tasks such as finding Minimum Cost Spanning Trees using Kruskal's and Prim's algorithms, solving the All-Pairs Shortest Paths problem with Floyd's algorithm, and implementing Dijkstra's algorithm for shortest paths. Additional experiments cover dynamic programming methods for the 0/1 Knapsack problem and various sorting algorithms, among others.

Uploaded by

shm23csds
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)
44 views32 pages

ADA Lab Manual

This lab manual outlines a series of programming experiments focused on algorithm design and implementation using C/C++. It includes tasks such as finding Minimum Cost Spanning Trees using Kruskal's and Prim's algorithms, solving the All-Pairs Shortest Paths problem with Floyd's algorithm, and implementing Dijkstra's algorithm for shortest paths. Additional experiments cover dynamic programming methods for the 0/1 Knapsack problem and various sorting algorithms, among others.

Uploaded by

shm23csds
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/ 32

ANALYSIS AND

DESIGN OF
ALGORITHM

LAB MANUAL
EVEN SEM
2024-25
Sl.No Experiment
s
1 Design and implement C/C++ Program to find Minimum Cost Spanning Tree of a given
connected undirected graph using Kruskal's algorithm.
2 Design and implement C/C++ Program to find Minimum Cost Spanning Tree of a given
connected undirected graph using Prim's algorithm.
3 a.​ Design and implement C/C++ Program to solve All-Pairs Shortest Paths problem using
Floyd's algorithm.
b.​Design and implement C/C++ Program to find the transitive closure using Warshal's
algorithm.
4 Design and implement C/C++ Program to find shortest paths from a given vertex in a
weighted
connected graph to other vertices using Dijkstra's algorithm.
5 Design and implement C/C++ Program to obtain the Topological ordering of vertices in a
given digraph.
6 Design and implement C/C++ Program to solve 0/1 Knapsack problem using Dynamic
Programming method.
7 Design and implement C/C++ Program to solve discrete Knapsack and continuous Knapsack
problems using greedy approximation method.
8 Design and implement C/C++ Program to find a subset of a given set S = {sl , s2,.....,sn} of n
positive integers whose sum is equal to a given positive integer d.
9 Design and implement C/C++ Program to sort a given set of n integer elements using
Selection Sort method and compute its time complexity. Run the program for varied values
of n> 5000 and record the time taken to sort. Plot a graph of the time taken versus n. The
elements can be read from a file or can be generated using the random number generator.
10 Design and implement C/C++ Program to sort a given set of n integer elements using Quick
Sort method and compute its time complexity. Run the program for varied values of n> 5000
and record the time taken to sort. Plot a graph of the time taken versus n. The elements can
be read from a file or can be generated using the random number generator.
11 Design and implement C/C++ Program to sort a given set of n integer elements using Merge
Sort method and compute its time complexity. Run the program for varied values of n> 5000,
and record the time taken to sort. Plot a graph of the time taken versus n. The elements can
be read from a file or can be generated using the random number generator.
12 Design and implement C/C++ Program for N Queen's problem using Backtracking.
1.Design and implement C/C++ Program to find Minimum Cost Spanning
Tree of a given connected undirected graph using Kruskal's algorithm.

#include<stdio.h>
#include<conio.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()
{
clrscr();
printf("\n\n\tImplementation of Kruskal's algorithm\n\n");
printf("\nEnter the no. of vertices\n");
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("\nThe edges of Minimum Cost Spanning Tree are\n\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("\n%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);
getch();
}
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;
}
2.Design and implement C/C++ Program to find Minimum Cost Spanning
Tree of a given connected undirected graph using Prim's algorithm.

#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("Spanning tree:");
for(i=0; i<n; i++) {
printf("\n");
for(j=0; j<n; j++)
printf("%d\t",S[i][j]);
}
printf("\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);
}

3.a.Design
and implement C/C++ Program to solve All-Pairs Shortest Paths
problem using Floyd's algorithm.

#include <iostream
using namespace std;
// defining the number of vertices
#define V 4
#define INF 9999
void printMatrix(int matrix[][V]);
// Implementing floyd warshall algorithm
void floydWarshall(int graph[][V]) {
int matrix[V][V], i, j, k;
for (i = 0; i < V; i++)
for (j = 0; j < V; j++)
matrix[i][j] = graph[i][j];
// Adding vertices individually
for (k = 0; k < V; k++) {
for (i = 0; i < V; i++) {
for (j = 0; j < V; j++) {
if (matrix[i][k] + matrix[k][j] < matrix[i][j])
matrix[i][j] = matrix[i][k] + matrix[k][j];
}
}
}
printMatrix(matrix);
}
void printMatrix(int matrix[][V]) {
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
if(i==j){
continue;
}
else if (matrix[i][j] == INF){
cout<<"no path exist between "<<i<<" and "<<j<<endl;
}
else{
cout<<"shortest path from "<<i<<" to "<<j<<" is "<<matrix[i][j]<<endl;
}
}
}
}
int main() {
int graph[V][V] = {{0,INF,-3,INF},
{5,0,4,INF},
{INF,INF,0,3},
{INF,-2,INF,0}};
floydWarshall(graph);
return 0;
// End of Program
}

3.bDesign and implement C/C++ Program to find the transitive closure using
Warshal's algorithm.

# include <stdio.h>
# include <conio.h>
int n,a[10][10],p[10][10];
void path()
{
int i,j,k;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
p[i][j]=a[i][j];
for(k=0;k<n;k++)
for(i=0;i<n;i++)
for(j=0;j<n;j++)
if(p[i][k]==1&&p[k][j]==1) p[i][j]=1;
}
void main()
{
int i,j;
clrscr();
printf("Enter the number of nodes:");
scanf("%d",&n);
printf("\nEnter the adjacency matrix:\n");
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
path();
printf("\nThe path matrix is showm below\n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
printf("%d ",p[i][j]);
printf("\n");
}
getch();
}

4.Design and implement C/C++ Program to find shortest paths from a given
vertex in a weighted connected graph to other vertices using Dijkstra's
algorithm.

#include <stdio.h>
#include <stdbool.h>
#define INF 99999
#define V 5 // Number of vertices

// A function to find the vertex with the minimum distance value, from the set of
vertices not yet included in shortest path tree
int minDistance(int dist[], bool sptSet[]) {
int min = INF, min_index;

for (int v = 0; v < V; v++)


if (sptSet[v] == false && dist[v] <= min)
min = dist[v], min_index = v;

return min_index;
}

// A utility function to print the constructed distance array


void printSolution(int dist[]) {
printf("Vertex \t\t Distance from Source\n");
for (int i = 0; i < V; i++)
printf("%d \t\t %d\n", i, dist[i]);
}

// Dijkstra's algorithm for adjacency matrix representation of the graph


void dijkstra(int graph[V][V], int src) {
int dist[V]; // The output array. dist[i] will hold the shortest distance from src to
i
bool sptSet[V]; // sptSet[i] will be true if vertex i is included in shortest path
tree

// Initialize all distances as INFINITE and sptSet[] as false


for (int i = 0; i < V; i++)
dist[i] = INF, sptSet[i] = false;

dist[src] = 0;

// Find shortest path for all vertices


for (int count = 0; count < V - 1; count++) {
int u = minDistance(dist, sptSet);
sptSet[u] = true;
for (int v = 0; v < V; v++)
if (!sptSet[v] && graph[u][v] && dist[u] != INF && dist[u] + graph[u][v]
< dist[v])
dist[v] = dist[u] + graph[u][v];
}

printSolution(dist);
}

// Driver code
int main() {
int graph[V][V] = {{0, 9, 6, 5, 3},
{9, 0, 0, 0, 0},
{6, 0, 0, 0, 0},
{5, 0, 0, 0, 0},
{3, 0, 0, 0, 0}};

dijkstra(graph, 0);
return 0;
}

5.Design and implement C/C++ Program to obtain the Topological ordering of


vertices in a given
digraph.

#include<stdio.h>
int a[10][10],n,indegre[10];
void find_indegre()
{ int j,i,sum;
for(j=0;j<n;j++)
{
sum=0;
for(i=0;i<n;i++)
sum+=a[i][j];
indegre[j]=sum;
}
}
void topology()
{
int i,u,v,t[10],s[10],top=-1,k=0;
find_indegre();
for(i=0;i<n;i++)
{
if(indegre[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)
{
indegre[v]--;
if(indegre[v]==0) s[++top]=v;
}
}
}
printf("The topological Sequence is:\n");
for(i=0;i<n;i++)
printf("%d ",t[i]);
}
void main()
{
int i,j;
clrscr();
printf("Enter number of jobs:");
scanf("%d",&n);
printf("\nEnter the adjacency matrix:\n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
}
topology();
}
#include <stdio.h>
#define MAX 10
int a[MAX][MAX], n, indegre[MAX];
// Function to calculate in-degrees of all vertices
void find_indegre() {
int i, j, sum;
for (j = 0; j < n; j++) {
sum = 0;
for (i = 0; i < n; i++) {
sum += a[i][j];
}
indegre[j] = sum;
}
}

// Function to perform topological sorting


void topology() {
int i, u, v, t[MAX], s[MAX], top = -1, k = 0;

// Find initial in-degrees


find_indegre();

// Push all vertices with in-degree 0 to stack


for (i = 0; i < n; i++) {
if (indegre[i] == 0) {
s[++top] = i;
}
}

// Process vertices from the stack


while (top != -1) {
u = s[top--];
t[k++] = u;

// Decrease the in-degree of all adjacent vertices


for (v = 0; v < n; v++) {
if (a[u][v] == 1) {
indegre[v]--;
if (indegre[v] == 0) {
s[++top] = v;
}
}
}
}

// Print the topological sequence


printf("The topological sequence is:\n");
for (i = 0; i < k; i++) {
printf("%d ", t[i]);
}
printf("\n");
}

int main() {
int i, j;
// Input the number of jobs (vertices)
printf("Enter number of jobs: ");
scanf("%d", &n);
// Input the adjacency matrix
printf("\nEnter the adjacency matrix:\n");
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
scanf("%d", &a[i][j]);
}
}
// Perform topological sorting
topology();
return 0;
}
6.Design and implement C/C++ Program to solve 0/1 Knapsack problem using
Dynamic
Programming method.

#include<stdio.h>
#include<conio.h>
int w[10],p[10],v[10][10],n,i,j,cap,x[10]={0};
int max(int i,int j)
{
return ((i>j)?i:j);
}
int knap(int i,int j)
{
int value;
if(v[i][j]<0)
{
if(j<w[i])
value=knap(i-1,j);
else
value=max(knap(i-1,j),p[i]+knap(i-1,j-w[i]));
v[i][j]=value;
}
return(v[i][j]);
}
void main()
{
int profit,count=0;
clrscr();
printf("\nEnter the number of elements\n");
scanf("%d",&n);
printf("Enter the profit and weights of the elements\n");
for(i=1;i<=n;i++)
{
printf("For item no %d\n",i);
scanf("%d%d",&p[i],&w[i]);
}
printf("\nEnter the capacity \n");
scanf("%d",&cap);
for(i=0;i<=n;i++)
for(j=0;j<=cap;j++)
if((i==0)||(j==0))
v[i][j]=0;
else
v[i][j]=-1;
profit=knap(n,cap);
i=n;
j=cap;
while(j!=0&&i!=0)
{
if(v[i][j]!=v[i-1][j])
{
x[i]=1;
j=j-w[i];
i--;
}
else
i--;
}
printf("Items included are\n");
printf("Sl.no\tweight\tprofit\n");
for(i=1;i<=n;i++)
if(x[i])
printf("%d\t%d\t%d\n",++count,w[i],p[i]);
printf("Total profit = %d\n",profit);
getch();

7.Design and implement C/C++ Program to solve discrete Knapsack and


continuous Knapsack problems using greedy approximation method.
#include<stdio.h>
int main()
{
float weight[50],profit[50],ratio[50],Totalvalue,temp,capacity,amount;
int n,i,j;
printf("Enter the number of items :");
scanf("%d",&n);
for (i = 0; i < n; i++)
{
printf("Enter Weight and Profit for item[%d] :\n",i);
scanf("%f %f", &weight[i], &profit[i]);
}
printf("Enter the capacity of knapsack :\n");
scanf("%f",&capacity);

for(i=0;i<n;i++)
ratio[i]=profit[i]/weight[i];

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


for (j = i + 1; j < n; j++)
if (ratio[i] < ratio[j])
{
temp = ratio[j];
ratio[j] = ratio[i];
ratio[i] = temp;

temp = weight[j];
weight[j] = weight[i];
weight[i] = temp;

temp = profit[j];
profit[j] = profit[i];
profit[i] = temp;
}
printf("Knapsack problems using Greedy Algorithm:\n");
for (i = 0; i < n; i++)
{
if (weight[i] > capacity)
break;
else
{
Totalvalue = Totalvalue + profit[i];
capacity = capacity - weight[i];
}
}
if (i < n)
Totalvalue = Totalvalue + (ratio[i]*capacity);
printf("\nThe maximum value is :%f\n",Totalvalue);
return 0;
}

8.Design and implement C/C++ Program to find a subset of a given set S = {sl ,
s2,.....,sn} of n positive integers whose sum is equal to a given positive integer
d.

#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;
}

9.Design and implement C/C++ Program to sort a given set of n integer


elements using Selection Sort method and compute its time complexity. Run
the program for varied values of n> 5000 and record the time taken to sort.
Plot a graph of the time taken versus n. The elements can be read
from a file or can be generated using the random number generator.

#include<stdio.h>
# include <time.h>
int main(){
int a[10000],i;
int j,temp,num;
clock_t st,et;
printf("Enter the number to give\n");
scanf("%d",&num);

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


{
a[i]=rand()%10000;

}
printf(“Array before sorting”);
for(i=0;i<n;i++)
{
printf("%d\t",a[i]);
}
st=clock();
for(i=0; i<num-1; i++){
for(j=i+1;j<num; j++){
if(a[i]>a[j]){
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
et=clock();
printf("Selection Sort in C\n");
for(i=0; i<num; i++){
printf("a[%d]=\t%d\n",i,a[i]);
}
printf(“Time taken :%f”,(et-st)/CLK_TCK);
return 0;
}

10.Design and implement C/C++ Program to sort a given set of n integer


elements using Quick Sort method and compute its time complexity. Run the
program for varied values of n> 5000 and record the time taken to sort. Plot
a graph of the time taken versus n. The elements can be read
from a file or can be generated using the random number generator.

# include <stdio.h>
# include <conio.h>
# include <time.h>

/* function that consider last element as pivot,


place the pivot at its exact position, and place
smaller elements to left of pivot and greater
elements to right of pivot. */
int partition (int a[], int start, int end)
{
int pivot = a[end]; // pivot element
int i = (start - 1);

for (int j = start; j <= end - 1; j++)


{
// If current element is smaller than the pivot
if (a[j] < pivot)
{
i++; // increment index of smaller element
int t = a[i];
a[i] = a[j];
a[j] = t;
}
}
int t = a[i+1];
a[i+1] = a[end];
a[end] = t;
return (i + 1);
}

/* function to implement quick sort */


void quick(int a[], int start, int end) /* a[] = array to be sorted, start = Starting index, end =
Ending index */
{
if (start < end)
{
int p = partition(a, start, end); //p is the partitioning index
quick(a, start, p - 1);
quick(a, p + 1, end);
}
}

/* function to print an array */


void printArr(int a[], int n)
{
int i;
for (i = 0; i < n; i++)
printf("%d ", a[i]);
}
int main()
{
int n, a[1000],k;
clock_t st,et;
double ts;
printf("\n Enter How many Numbers: ");
scanf("%d", &n);
printf("\nThe Random Numbers are:\n");
for(k=1; k<=n; k++)
{
a[k]=rand();
printf("%d\t",a[k]);
}
st=clock();
printf("Before sorting array elements are - \n");
printArr(a, n);
quick(a, 0, n - 1); Template tag is a special syntax used within Django templates to perform
logic or control flow operations, such as conditional statements, loops, or including other
templates. Template tags are enclosed within {% %} delimiters.

printf("\nAfter sorting array elements are - \n");


printArr(a, n);
et=clock();
ts=(double)(et-st)/CLOCKS_PER_SEC;
printf("\nSorted Numbers are: \n ");
for(k=1; k<=n; k++)
printf("%d\t", a[k]);
printf("\nThe time taken is %e",ts);
}

11.Design and implement C/C++ Program to sort a given set of n integer


elements using Merge Sort method and compute its time complexity. Run the
program for varied values of n> 5000, and record the time taken to sort. Plot a
graph of the time taken versus n. The elements can be read from a file or can
be generated using the random number generator.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

// Merge two subarrays of arr[]


// First subarray is arr[l..m]
// Second subarray is arr[m+1..r]
void merge(int arr[], int l, int m, int r) {
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;

// Create temporary arrays


int L[n1], R[n2];

// Copy data to temporary arrays L[] and R[]


for (i = 0; i < n1; i++)
L[i] = arr[l + i];
for (j = 0; j < n2; j++)
R[j] = arr[m + 1 + j];

// Merge the temporary arrays back into arr[l..r]


i = 0; // Initial index of first subarray
j = 0; // Initial index of second subarray
k = l; // Initial index of merged subarray
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}

// Copy the remaining elements of L[], if any


while (i < n1) {
arr[k] = L[i];
i++;
k++;
}

// Copy the remaining elements of R[], if any


while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}

// Main function to perform merge sort


void mergeSort(int arr[], int l, int r) {
if (l < r) {
int m = l + (r - l) / 2;

// Sort first and second halves


mergeSort(arr, l, m);
mergeSort(arr, m + 1, r);

// Merge the sorted halves


merge(arr, l, m, r);
}
}

// Function to generate n random integers and store them in arr[]


void generateRandomNumbers(int arr[], int n) {
srand(time(NULL));
for (int i = 0; i < n; i++) {
arr[i] = rand() % 1000; // Generate random integers between 0 and 999
}
}

int main() {
FILE *fp;
fp = fopen("time_complexity_data.txt", "w");
if (fp == NULL) {
printf("Error opening file!\n");
exit(1);
}

int n_values[] = {5000, 10000, 15000, 20000}; // Change or add more values as needed
int num_values = sizeof(n_values) / sizeof(n_values[0]);

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


int n = n_values[i];
int arr[n];
// Generate random numbers
generateRandomNumbers(arr, n);

// Record starting time


clock_t start_time = clock();

// Perform Merge Sort


mergeSort(arr, 0, n - 1);

// Record ending time


clock_t end_time = clock();

// Calculate the time taken


double time_taken = ((double)(end_time - start_time)) / CLOCKS_PER_SEC;

// Print the size of array and the time taken to sort


printf("n = %d, Time taken: %f seconds\n", n, time_taken);
fprintf(fp, "%d %f\n", n, time_taken);
}

fclose(fp);
return 0;
}

12.Design and implement C Program for N Queen's problem using Backtracking.

#include <stdio.h>
#include <stdbool.h>

#define N 8 // Define the size of the chessboard

// Function to print the solution


void printSolution(int board[N][N]) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++)
printf("%d ", board[i][j]);
printf("\n");
}
}

// Function to check if a queen can be placed on board[row][col]


bool isSafe(int board[N][N], int row, int col) {
int i, j;

// Check this row on the left side


for (i = 0; i < col; i++)
if (board[row][i])
return false;

// Check upper diagonal on left side


for (i = row, j = col; i >= 0 && j >= 0; i--, j--)
if (board[i][j])
return false;

// Check lower diagonal on left side


for (i = row, j = col; j >= 0 && i < N; i++, j--)
if (board[i][j])
return false;

return true;
}

// Recursive function to solve N Queen problem


bool solveNQUtil(int board[N][N], int col) {
// Base case: If all queens are placed then return true
if (col >= N)
return true;

// Consider this column and try placing this queen in all rows one by one
for (int i = 0; i < N; i++) {
// Check if the queen can be placed on board[i][col]
if (isSafe(board, i, col)) {
// Place this queen in board[i][col]
board[i][col] = 1;

// Recur to place rest of the queens


if (solveNQUtil(board, col + 1))
return true;
// If placing queen in board[i][col] doesn't lead to a solution, then remove queen from
board[i][col]
board[i][col] = 0; // Backtrack
}
}

// If the queen cannot be placed in any row in this column col, then return false
return false;
}

// Main function to solve N Queen problem


bool solveNQ() {
int board[N][N] = { {0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0} };

if (solveNQUtil(board, 0) == false) {
printf("Solution does not exist");
return false;
}

printSolution(board);
return true;
}

int main() {
solveNQ();
return 0;
}

ADDITIONAL PROGRAMS
1.Find the binomial co-efficient using dynamic programming.

#include<stdio.h>
#include<conio.h>
long int bin(int n,int k)
{
int i,j;
long int arr[20][20];
for(i=0;i<=n;i++)
{
​ for(j=0;j<=(k<i?k:i);j++)
​ {
​ ​ if(i==j||j==0)
​ ​ {
​ ​ ​ arr[i][j]=1;
​ ​ }
​ ​ else
​ ​ {
​ ​ ​ arr[i][j]=arr[i-1][j]+arr[i-1][j-1];
​ ​ }
​ }
}
return(arr[n][k]);
}
void main()
{
int n,k;
clrscr();
printf("\nEnter the value of n ");
scanf("%d",&n);
printf("\nEnter the value of k ");
scanf("%d",&k);
if(n<0||k<0||k>n)
{
​ printf("\nValue cannot be calculated!!");
}
else
{
​ printf("\nThe binomial coefficient is %ld.",bin(n,k));
}
getch();
}
2.Find the minimum cost spanning tree of a given undirected graph using Prim's algorithm.

#include<stdio.h>
#include<conio.h>
void main()
{
int a[20][20],add[20],f[20][20],min,posx,posy,i,j,k,n,tot,flag=0,weight=0;
clrscr();
tot=0;
printf("\nEnter the value of n ");
scanf("%d",&n);
printf("\nEnter the adjacency matrix ");
for(i=0;i<n;i++)
{
​ add[i]=0;
​ for(j=0;j<n;j++)
​ {
​ ​ scanf("%d",&a[i][j]);
​ ​ f[i][j]=0;
​ }
}
add[0]=1;
while(flag==0)
{
​ flag=1;
​ min=9999;
​ for(i=0;i<n;i++)
​ {
​ ​ if(add[i]==1)
​ ​ {
​ ​ ​ for(j=0;j<n;j++)
​ ​ ​ {
​ ​ ​ ​ if(add[j]==0&&a[i][j]!=0&&a[i][j]<min)
​ ​ ​ ​ {
​ ​ ​ ​ ​ min=a[i][j];
​ ​ ​ ​ ​ posx=i;
​ ​ ​ ​ ​ posy=j;
​ ​ ​ ​ }
​ ​ ​ }
​ ​ }
​ }
​ if(min!=9999)
​ {
​ ​ f[posx][posy]=min;
​ ​ f[posy][posx]=min;
​ ​ weight=weight+f[posx][posy];
​ ​ tot++;
​ ​ flag=0;
​ ​ add[posx]=1;
​ ​ add[posy]=1;
​ }
}
if(tot!=n-1)
{
​ printf("\nMinimum spannin does not exist!!");
}
else
{
​ printf("\nMinimum spanning tree with weight=%d is ",weight);
​ for(i=0;i<n;i++)
​ {
​ ​ printf("\n");
​ ​ for(j=0;j<n;j++)
​ ​ {
​ ​ ​ printf("%d ",f[i][j]);
​ ​ }
​ }
}
getch();
}

You might also like