Sie sind auf Seite 1von 38

Design and Analysis of Algorithms

Prog. – 1: Find square root of a number. Can we use Divide & Conquer approach for this
problem?

LOGIC:
1. Select a number n (a good first guess would be m/2) < m.
2. if n 2 > m, n <- n-1 and repeat step 2, else goto step 3.
3. if n 2 < m, start adding 0.1 to n.
4. compute n 2 , until n 2 > m.
5. n <- n-0.1; repeat steps 3, 4, 5, using 0.01 instead of 0.1, etc.

Program :
#include <stdio.h>
void main()
{
float n,m,root,num;

printf("Enter any number: ");


scanf("%f", &m);

n=m/2;
while(n*n>m)
{
n=n-1;
}
while(n*n<m)
{
n=n+0.1;
if(n*n>m)
{
n=n-0.1;
n=n+0.01;
}
}
if(n*n>m)
{
//n=n-0.1;
n=n-0.01;
}
printf("%2f ",n);
printf("\n");
}

INPUT:
N number- 49

OUTPUT:
Square root =7.0000

1|Page
Design and Analysis of Algorithms

Prog. – 2: Determine smallest divisor of an integer.

LOGIC:
1. If n is even return 2 as the divisor, Else
2. (a) Let r = √ n
(b) initialize divisor d to 3;
(c) while(n%d 0 and d < r) do: d d+2.
(d) If(n%d = 0) then return d; else return 1;

Program :
#include<stdio.h>
void main()
{
int d,r,n;
scanf("%d",&n);
if(n%2==0)
{
printf("2 is ans");
}

else
{
r=n*(n);
d=3;
while((n%d!=0)&&d<r)
{
d=d+2;
}
if(n%d==0)
{
printf("ans is %d",d);
}
else
{
printf("ans is 1");
}
printf("\n");
}
}

INPUT:
N number- 35

OUTPUT:
Smallest divisor =5

2|Page
Design and Analysis of Algorithms

Prog. – 3: For a given value of n, Generate prime numbers <=n

LOGIC:

int main()
{
unsigned long long int i,j;
int *primes;
int z = 1,n;
primes = malloc(sizeof(int) * limit);
Scanf(“%d”,&n);
for (i = 2;i < limit; i++)
primes[i] = 1;
for (i = 2;i < limit; i++)
if (primes[i])
for (j = i;i * j < limit; j++)
primes[i * j] = 0;
printf("\nPrime numbers in range 1 to 100 are: \n");
for (i = 2;i < limit; i++)
if (primes[i])
printf("%d\n", i);
return 0;
}

Program :
#include <stdio.h>

int main()
{
int i, j, start, end;
int isPrime; //isPrime is used as flag variable

/* Read upper and lower limit to print prime */


printf("Enter lower limit: ");
scanf("%d", &start);
printf("Enter upper limit: ");
scanf("%d", &end);

printf("All prime numbers between %d to %d are:\n", start, end);

/* Find all Prime numbers between 1 to n */


for(i=start; i<=end; i++)
{
/* Assume that the current number is Prime */
isPrime = 1;

/* Check if the current number i is prime or not */


for(j=2; j<=i/2; j++)

3|Page
Design and Analysis of Algorithms

{
/*
* If i is divisible by any number other than 1 and self
* then it is not prime number
*/
if(i%j==0)
{
isPrime = 0;
break;
}
}

/* If the number is prime then print */


if(isPrime==1)
{
printf("%d, ", i);
}
}

return 0;
}

INPUT :
Enter lower limit: 1
Enter upper limit: 100

OUTPUT:
All prime numbers between 1 to 100 are:
1, 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97,

4|Page
Design and Analysis of Algorithms

Prog. – 4: Find Xn . Iterative and recursive algorithms are


possible.

LOGIC:

Recursive :
int main()
{
int pow, num;
long result;
printf("Enter a number: ");
scanf("%d", &num);
printf("Enter it's power: ");
scanf("%d", &pow);
result = power(num, pow);
printf("%d^%d is %ld", num, pow, result);
return 0;
}
long power (int num, int pow)
{
if (pow)
{ return (num * power(num, pow - 1)); }
return 1;
}

Iterative:
int power(int x, unsigned int y)
{
int res = 1; // Initialize result
while (y > 0)
{
// If y is odd, multiply x with result
if (y & 1)
res = res*x;
// n must be even now
y = y>>1; // y = y/2
x = x*x; // Change x to x^2
}
return res;
}

Program:
#include <stdio.h>

int main()
{
int base, exponent, counter, result = 1;
printf("Enter base and exponent \n");

5|Page
Design and Analysis of Algorithms

scanf("%d %d", &base, &exponent);

result = getPower(base, exponent);

printf("%d^%d = %d \n", base, exponent, result);


return 0;
}
/*
* Function to calculate base^exponent using recursion
*/
int getPower(int base, int exponent)
{
/* Recursion termination condition,
* Anything^0 = 1
*/
int result;
if(exponent == 0)
{
return 1;
}
result = getPower(base, exponent/2);
if(exponent%2 == 0)
{
/*Exponent is even */
return result*result;
}
else
{
/*Exponent is odd */
return base*result*result;
}
}

INPUT:
Enter base and exponent
3
5

OUTPUT :
3^5 = 243

6|Page
Design and Analysis of Algorithms

Prog. - 5: Determine product of 2 integers (a * b) as repeated sums. Iterative and recursive


algorithms are possible.

Code (recursion):
#include<stdio.h>
int multiply(int,int);
int main()
{
int a,b,product;
printf("Enter first integers:");
scanf("%d",&a);
printf("Enter second integers:");
scanf("%d",&b);
product = multiply(a,b);
printf("Multiplication of two integers is %d \n",product);
return 0;
}

int multiply(int a,int b)


{
static int product=0,i=0;
if(i < a)
{
product = product + b;
i++;
multiply(a,b);
}
return product;
}

INPUT:
Enter first integers:2
Enter second integers:3

OUTPUT:
Multiplication of two integers is 6

7|Page
Design and Analysis of Algorithms

Code (Iterative):

#include<stdio.h>
int multiply(int,int);
int main()
{
int a,b,product;
printf("Enter first integers:");
scanf("%d",&a);
printf("Enter second integers:");
scanf("%d",&b);
product = multiply(a,b);
printf("Multiplication of two integers is %d \n",product);
return 0;
}

int multiply(int a,int b)


{
int product =0,i=0;
while(i < a)
{
product = product + b;
i++;
}
return product;
}

INPUT:
Enter first integers:2
Enter second integers:3

OUTPUT:
Multiplication of two integers is 6

8|Page
Design and Analysis of Algorithms

Prog. - 6: Find Factorial of n. Iterative and recursive algorithms are possible.

Code (Iterative):
#include <stdio.h>
// Iterative function to find factorial of a number using for loop
unsigned long factorial(int n)
{
unsigned long fact = 1;
int i;
for (i = 1; i <= n; i++)
{
fact = fact * i;
}
return fact;
}
int main()
{
int n = 5;
printf("The Factorial of %d is %lu", n, factorial(n));
printf("\n");
return 0;
}

Output :

The Factorial of 5 is 120

9|Page
Design and Analysis of Algorithms

Code (recursive) :

#include <stdio.h>
// Recursive function to find factorial of a number
unsigned long factorial(int n)
{
// base case: if n is 0 or 1
if (n < 1)
{
return 1;
}
// use the recurrence relation
return n * factorial(n - 1);
}
int main()
{
int n = 5;
printf("The Factorial of %d is %lu", n, factorial(n));
return 0;
}

Output :

The Factorial of 5 is 120

10 | P a g e
Design and Analysis of Algorithms

Prog. - 7: Generate Fibonacci series up to n terms Iterative and recursive algorithms are
possible.

Code (Iterative):
/* Fibonacci series up to n terms Iterative */

#include <stdio.h>
int main()
{
int a, b, c, start, end;
printf("Enter starting term: ");
scanf("%d", &start);
printf("Enter end term: ");
scanf("%d", &end);
// Fibonacci magic initialization
a = 0;
b = 1;
c = 0;
printf("Fibonacci terms: \n");
// Iterate through terms
while(c <= end)
{
// If current term is greater than start term
if(c >= start)
{
printf("%d, ", c);
}
a = b; // Copy n-1 to n-2
b = c; // Copy current to n-1
c = a + b; // New term
}
return 0;
}

Output :

Enter starting term: 1


Enter end term: 40
Fibonacci terms:
1, 1, 2, 3, 5, 8, 13, 21, 34,

11 | P a g e
Design and Analysis of Algorithms

Code (recursive):
/* Fibonacci series up to n terms recursive */
#include<stdio.h>
long factorial(int);
int main()
{
int n;
long f;
printf("Enter an integer to find factorial\n");
scanf("%d", &n);
if (n < 0)
{
printf("Negative integers are not allowed.\n");
}
else
{
f = factorial(n);
printf("%d! = %ld\n", n, f);
}
return 0;
}
long factorial(int n)
{
if (n == 0)
{
return 1;
}
else
{
return(n * factorial(n-1));
}
}

Output :

Enter an integer to find factorial


5
5! = 120

12 | P a g e
Design and Analysis of Algorithms

Prog. - 8: Determine product of 2 large integers using multiplication of their digits. For
simplicity, assume both numbers to have same number of digits. This assumption can be
relaxed subsequently.

Code :

#include<stdio.h>
int main()
{
int n,i,j,k,c,m,r,x,t,h,y;
printf("enter number of N:");
scanf("%d",&n);//no of test cases
for(i=0;i<n;i++)
{
char A[10002],B[10002];
int c1=0,c2=0,l;
printf("enter first number:");
scanf("%s",A);
printf("enter second number:");
scanf("%s",B);
printf("Answer:");//sacnning the no.s
for(j=0;A[j]!='\0';j++)
c1++;
for(j=0;B[j]!='\0';j++)
c2++;
l=29999;int a[30002]={0};
for(j=c2-1;j>=0;j--)
{
c=0;
x=l-1;

for(k=c1-1;k>=0;k--)
{
h=(int)B[j]-48;
y=(int)A[k]-48;
r=(h*y)+c;//multiply the last digit of B with all the digits of A.
m=r%10;
r=r/10;c=r;//c is the carry
a[x]=m+a[x];
if(a[x]>9)
{
a[x]=a[x]%10;
a[x-1]=a[x-1]+1;//adding 1 to previous posn of result in case of overflow.since only
maximum 1 can be the 1st digit.

x--;

13 | P a g e
Design and Analysis of Algorithms

}
l--;
a[x]=a[x]+c;

int flag=0;
for(k=0;k<=29998;k++)
{
if(a[k]!=0){
printf("%d",a[k]);
flag=1;
}
else if(a[k]==0 && flag==1)
printf("0");
}
if(flag==0)
printf("0");
printf("\n");
}
return 0;
}

Output :

enter number of N:3


enter any number:2
enter any number:2
Answer:4
enter any number:3
enter any number:3
Answer:9
enter any number:4
enter any number:4
Answer:16

14 | P a g e
Design and Analysis of Algorithms

Prog. - 9: Binary Search of an ordered array. Iterative and Recursive algorithms are possible.

Code (Iterative):

#include <stdio.h>
// A iterative binary search function. It returns location of x in
// given array arr[l..r] if present, otherwise -1
int binarySearch(int arr[], int l, int r, int x)
{
while (l <= r)
{
int m = l + (r-l)/2;
// Check if x is present at mid
if (arr[m] == x)
return m;
// If x greater, ignore left half
if (arr[m] < x)
l = m + 1;
// If x is smaller, ignore right half
else
r = m - 1;
}
// if we reach here, then element was not present
return -1;
}

int main(void)
{
int arr[] = {2, 3, 4, 10, 40};
int n = sizeof(arr)/ sizeof(arr[0]);
int x = 10;
int result = binarySearch(arr, 0, n-1, x);
(result == -1)? printf("Element is not present in array")
: printf("Element is present at index %d \n", result);
return 0;
}

Output :

Element is present at index 3

15 | P a g e
Design and Analysis of Algorithms

Code (Recursive):

#include<stdio.h>
#include<stdlib.h>
#define size 10

int binsearch(int[], int, int, int);

int main()
{
int num, i, key, position;
int low, high, list[size];

printf("\nEnter the total number of elements \n");


scanf("%d", &num);

printf("\nEnter the elements of list : \n");


for (i = 0; i < num; i++)
{
printf("enter number :");
scanf("%d", &list[i]);
}

low = 0;
high = num - 1;
printf("\nEnter element to be searched :");
scanf("%d", &key);
position = binsearch(list, key, low, high);

if (position != -1)
{
printf("\n Number present at %d \n", (position + 1));
}
else
{
printf("\n The number is not present in the list \n");
}
return (0);
}

// Binary Search function


int binsearch(int a[], int x, int low, int high)
{
int mid;
if (low > high)
return -1;
mid = (low + high) / 2;
if (x == a[mid])

16 | P a g e
Design and Analysis of Algorithms

{
return (mid);
}
else if (x < a[mid])
{
binsearch(a, x, low, mid - 1);
}
else
{
binsearch(a, x, mid + 1, high);
}
}

Output :

Enter the total number of elements


5

Enter the elements of list :


enter number :11
enter number :22
enter number :33
enter number :44
enter number :55

Enter element to be searched :33

Number present at 3

17 | P a g e
Design and Analysis of Algorithms

Prog. - 10: Sort a given sequence of numbers using (a) Bubble Sort, and (b) Merge Sort

(a) Bubble Sort :

Code :

#include <stdio.h>

int main()
{
int array[100], n, c, d, swap;

printf("Enter number of elements\n");


scanf("%d", &n);

printf("Enter %d integers\n", n);


for (c = 0; c < n; c++)
{
scanf("%d", &array[c]);
}

for (c = 0 ; c < ( n - 1 ); c++)


{
for (d = 0 ; d < n - c - 1; d++)
{
if (array[d] > array[d+1]) /* For decreasing order use < */
{
swap = array[d];
array[d] = array[d+1];
array[d+1] = swap;
}
}
}

printf("Sorted list in ascending order:\n");


for ( c = 0 ; c < n ; c++ )
{
printf("%d\n", array[c]);
}
return 0;
}

18 | P a g e
Design and Analysis of Algorithms

Output :

Enter number of elements


6
Enter 6 integers
7
5
1
6
9
12
Sorted list in ascending order:
1
5
6
7
9
12

19 | P a g e
Design and Analysis of Algorithms

(b) Merge Sort :

Code :

#include<stdio.h>

void mergesort(int a[],int i,int j);


void merge(int a[],int i1,int j1,int i2,int j2);

int main()
{
int a[30],n,i;
printf("Enter no of elements:");
scanf("%d",&n);
printf("Enter array elements:");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
mergesort(a,0,n-1);
printf("\nSorted array is :");
for(i=0;i<n;i++)
{
printf("%d ",a[i]);
}
return 0;
}

void mergesort(int a[],int i,int j)


{
int mid;
if(i<j)
{
mid=(i+j)/2;
mergesort(a,i,mid); //left recursion
mergesort(a,mid+1,j); //right recursion
merge(a,i,mid,mid+1,j); //merging of two sorted sub-arrays
}
}

void merge(int a[],int i1,int j1,int i2,int j2)


{
int temp[50]; //array used for merging
int i,j,k;
i=i1; //beginning of the first list
j=i2; //beginning of the second list
k=0;

20 | P a g e
Design and Analysis of Algorithms

while(i<=j1 && j<=j2) //while elements in both lists


{
if(a[i]<a[j])
{
temp[k++]=a[i++];
}
else
{
temp[k++]=a[j++];
}
}

while(i<=j1) //copy remaining elements of the first list


{
temp[k++]=a[i++];
}
while(j<=j2) //copy remaining elements of the second list
{
temp[k++]=a[j++];
}
//Transfer elements from temp[] back to a[]
for(i=i1,j=0;i<=j2;i++,j++)
{
a[i]=temp[j];
}
}

Output :

Enter no of elements:10
Enter array elements:
14
99
35
2
45
28
57
62
78
82

Sorted array is :2 14 28 35 45 57 62 78 82 99

21 | P a g e
Design and Analysis of Algorithms

Prog. - 11: Knapsack problem using Greedy algorithm.

Code :

# include<stdio.h>

void knapsack(int n, float weight[], float profit[], float capacity)


{
float x[20], tp = 0;
int i, j, u;
u = capacity;

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


{
x[i] = 0.0;
}

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


{
if (weight[i] > u)
{
break;
}
else
{
x[i] = 1.0;
tp = tp + profit[i];
u = u - weight[i];
}
}

if (i < n)
{
x[i] = u / weight[i];
}
tp = tp + (x[i] * profit[i]);

printf("\nThe result vector is:- ");


for (i = 0; i < n; i++)
{
printf("%f\t", x[i]);
}
printf("\nMaximum profit is:- %f", tp);
}

int main()
{
float weight[20], profit[20], capacity;

22 | P a g e
Design and Analysis of Algorithms

int num, i, j;
float ratio[20], temp;

printf("\nEnter the no. of objects:- ");


scanf("%d", &num);

printf("\nEnter the wts and profits of each object:- ");


for (i = 0; i < num; i++)
{
scanf("%f %f", &weight[i], &profit[i]);
}

printf("\nEnter the capacityacity of knapsack:- ");


scanf("%f", &capacity);

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


{
ratio[i] = profit[i] / weight[i];
}

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


{
for (j = i + 1; j < num; 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;
}
}
}

knapsack(num, weight, profit, capacity);


return(0);
}

23 | P a g e
Design and Analysis of Algorithms

Output :

Enter the no. of objects:- 5

Enter the wts and profits of each object:- 6


5
1
2
3
7
9
4
5
6

Enter the capacityacity of knapsack:- 15

The result vector is:- 1.000000 1.000000 1.000000 1.000000 0.000000


Maximum profit is:- 20.000000

24 | P a g e
Design and Analysis of Algorithms

Prog. - 12: Solution of Rod-cutting problem using Dynamic Programming algorithm.

Code :

// A Dynamic Programming solution for Rod cutting problem


#include<stdio.h>
#include<limits.h>
// A utility function to get the maximum of two integers
int max(int a, int b) { return (a > b)? a : b;}

/* Returns the best obtainable price for a rod of length n and price[] as prices of different pieces */
int cutRod(int price[], int n)
{
int val[n+1];
val[0] = 0;
int i, j;

// Build the table val[] in bottom up manner and return the last entry from the table
for (i = 1; i<=n; i++)
{
int max_val = INT_MIN;
for (j = 0; j < i; j++)
{
max_val = max(max_val, price[j] + val[i-j-1]);
}
val[i] = max_val;
}
return val[n];
}

/* Driver program to test above functions */


int main()
{
int arr[] = {1, 5, 8, 9, 10, 17, 17, 20};
int size = sizeof(arr)/sizeof(arr[0]);
printf("Maximum Obtainable Value is %dn \n", cutRod(arr, size));
return 0;
}

Output :

Maximum Obtainable Value is 22n

25 | P a g e
Design and Analysis of Algorithms

Prog. - 13: Matrix multiplication using Dynamic Programming algorithm.

Code :

#define INFY 999999999


#include<stdio.h>
long int m[20][20];
int s[20][20];
int p[20],i,j,n;

void print_optimal(int i,int j)


{
if (i == j)
{
printf(" A%d ",i);
}
else
{
printf(" ( ");
print_optimal(i, s[i][j]);
print_optimal(s[i][j] + 1, j);
printf(" ) ");
}
}

void matmultiply(void)
{
long int q;
int k;
for(i=n;i>0;i--)
{
for(j=i;j<=n;j++)
{
if(i==j)
m[i][j]=0;
else
{
for(k=i;k<j;k++)
{
q=m[i][k]+m[k+1][j]+p[i-1]*p[k]*p[j];
if(q<m[i][j])
{
m[i][j]=q;
s[i][j]=k;
}
}
}
}

26 | P a g e
Design and Analysis of Algorithms

}
}

void main()
{
int k;
printf("Enter the no. of elements: ");
scanf("%d",&n);
for(i=1;i<=n;i++)

for(j=i+1;j<=n;j++)
{
m[i][i]=0;
m[i][j]=INFY;
s[i][j]=0;
}
printf("\nEnter the dimensions: \n");
for(k=0;k<=n;k++)
{
printf("P%d: ",k);
scanf("%d",&p[k]);
}
matmultiply();
printf("\nCost Matrix M:\n");

for(i=1;i<=n;i++)
for(j=i;j<=n;j++)

printf("m[%d][%d]: %ld\n",i,j,m[i][j]);
printf("\nMatrix S for k values:\n");

for(i=1;i<=n;i++)
for(j=i;j<=n;j++)

printf("m[%d][%d]: %d\n",i,j,s[i][j]);
i=1,j=n;

printf("\n MULTIPLICATION SEQUENCE : ");


print_optimal(i,j);
printf("\n");
}

Output :

Enter the no. of elements: 3

Enter the dimensions:


P0: 4

27 | P a g e
Design and Analysis of Algorithms

P1: 5
P2: 6
P3: 7

Cost Matrix M:
m[1][1]: 0
m[1][2]: 120
m[1][3]: 288
m[2][2]: 0
m[2][3]: 210
m[3][3]: 0

Matrix S for k values:


m[1][1]: 0
m[1][2]: 1
m[1][3]: 2
m[2][2]: 0
m[2][3]: 2
m[3][3]: 0

MULTIPLICATION SEQUENCE : ( ( A1 A2 ) A3 )

28 | P a g e
Design and Analysis of Algorithms

Prog. - 14: Breadth First Search (BFS) in a binary tree.

Code :

#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node* left, *right;
};

void printGivenLevel(struct node* root, int level);


int height(struct node* node);
struct node* newNode(int data);
void printLevelOrder(struct node* root)
{
int h = height(root);
int i;
for (i=1; i<=h; i++)
{
printGivenLevel(root, i);
}
}

void printGivenLevel(struct node* root, int level)


{
if (root == NULL)
{
return;
}
if (level == 1)
{
printf("%d ", root->data);
}
else if (level > 1)
{
printGivenLevel(root->left, level-1);
printGivenLevel(root->right, level-1);
}
}

int height(struct node* node)


{
if (node==NULL)
{
return 0;
}

29 | P a g e
Design and Analysis of Algorithms

else
{
int lheight = height(node->left);
int rheight = height(node->right);
if (lheight > rheight)
{
return(lheight+1);
}
else
{
return(rheight+1);
}
}
}
struct node* newNode(int data)
{
struct node* node = (struct node*) malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return(node);
}

int main()
{
struct node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
printf("Level Order traversal of binary tree is \n");
printLevelOrder(root);
printf("\n");
return 0;
}

Output:

Level Order traversal of binary tree is


12345

30 | P a g e
Design and Analysis of Algorithms

Prog. - 15: Depth First Search (DFS) in a binary tree.

Code :

#include<stdio.h>

void DFS(int);
int G[10][10],visited[10],n;
void main()
{
int i,j;
printf("Enter number of vertices:");
scanf("%d",&n);
//read the adjecency matrix
printf("\nEnter adjacency matrix of the graph:");

for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&G[i][j]);
//visited is initialized to zero
for(i=0;i<n;i++)
visited[i]=0;
DFS(0);
}
void DFS(int i)
{
int j;
printf("\n%d",i);
visited[i]=1;

for(j=0;j<n;j++)
if(!visited[j]&&G[i][j]==1)
DFS(j);
printf("\n");
}

31 | P a g e
Design and Analysis of Algorithms

Output :

Enter number of vertices:8


Enter adjacency matrix of the graph:0 1 1 1 1 0 0 0

10000100
10000100
10000010
10000010
01100001
00011001
00000110

0
1
5
2

7
6
3

32 | P a g e
Design and Analysis of Algorithms

Prog. - 16: 8-Puzzle and 16-Puzzle.

Code (8-puzzle) :

#include <stdio.h>

int main(void)
{

int solution[3][3] = {{1, 2, 3},{8, 0, 4}, {7, 6, 5}};

int i = 0,
j = 0;
for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
{

printf("%d ", solution[i][j]);


}
printf("\n");
}
return(0);
}

Output :

1 2 3
8 0 4
7 6 5

33 | P a g e
Design and Analysis of Algorithms

Code (16-Puzzle) :

#include<stdio.h>

int m=0,n=4;
int cal(int temp[10][10],int t[10][10])
{
int i,j,m=0;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
{
if(temp[i][j]!=t[i][j])
m++;
}
return m;
}

int check(int a[10][10],int t[10][10])


{
int i,j,f=1;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
if(a[i][j]!=t[i][j])
f=0;
return f;
}

void main()
{
int p,i,j,n=4,a[10][10],t[10][10],temp[10][10],r[10][10];
int m=0,x=0,y=0,d=1000,dmin=0,l=0;
printf("\nEnter the matrix to be solved,space with zero :\n");
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);

printf("\nEnter the target matrix,space with zero :\n");


for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&t[i][j]);

printf("\nEntered Matrix is :\n");


for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
printf("%d\t",a[i][j]);
printf("\n");

34 | P a g e
Design and Analysis of Algorithms

printf("\nTarget Matrix is :\n");


for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
printf("%d\t",t[i][j]);
printf("\n");
}

while(!(check(a,t)))
{
l++;
d=1000;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
{
if(a[i][j]==0)
{
x=i;
y=j;
}
}

//To move upwards


for(i=0;i<n;i++)
for(j=0;j<n;j++)
temp[i][j]=a[i][j];

if(x!=0)
{
p=temp[x][y];
temp[x][y]=temp[x-1][y];
temp[x-1][y]=p;
}
m=cal(temp,t);
dmin=l+m;
if(dmin<d)
{
d=dmin;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
r[i][j]=temp[i][j];
}

//To move downwards


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

35 | P a g e
Design and Analysis of Algorithms

temp[i][j]=a[i][j];
if(x!=n-1)
{
p=temp[x][y];
temp[x][y]=temp[x+1][y];
temp[x+1][y]=p;
}
m=cal(temp,t);
dmin=l+m;
if(dmin<d)
{
d=dmin;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
r[i][j]=temp[i][j];
}

//To move right side


for(i=0;i<n;i++)
for(j=0;j<n;j++)
temp[i][j]=a[i][j];
if(y!=n-1)
{
p=temp[x][y];
temp[x][y]=temp[x][y+1];
temp[x][y+1]=p;
}
m=cal(temp,t);
dmin=l+m;
if(dmin<d)
{
d=dmin;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
r[i][j]=temp[i][j];
}

//To move left


for(i=0;i<n;i++)
for(j=0;j<n;j++)
temp[i][j]=a[i][j];
if(y!=0)
{
p=temp[x][y];
temp[x][y]=temp[x][y-1];
temp[x][y-1]=p;
}
m=cal(temp,t);

36 | P a g e
Design and Analysis of Algorithms

dmin=l+m;
if(dmin<d)
{
d=dmin;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
r[i][j]=temp[i][j];
}

printf("\nCalculated Intermediate Matrix Value :\n");


for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
printf("%d\t",r[i][j]);
printf("\n");
}
for(i=0;i<n;i++)
for(j=0;j<n;j++)
{
a[i][j]=r[i][j];
temp[i][j]=0;
}
printf("Minimum cost : %d\n",d);
}
}

Output :

Enter the matrix to be solved,space with zero:


1
2
3
4
5
6
0
8
9
10
7
11
13
14
15
12

Enter the target matrix,space with zero :


1

37 | P a g e
Design and Analysis of Algorithms

2
3
4
5
6
7
8
9
10
11
12
13
14
15
0

Entered Matrix is :
1 2 3 4
5 6 0 8
9 10 7 11
13 14 15 12

Target Matrix is :
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 0

Calculated Intermediate Matrix Value :


1 2 3 4
5 6 7 8
9 10 0 11
13 14 15 12
Minimum cost : 4

Calculated Intermediate Matrix Value :


1 2 3 4
5 6 7 8
9 10 11 0
13 14 15 12
Minimum cost : 4

Calculated Intermediate Matrix Value :


1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 0
Minimum cost : 3

38 | P a g e

Das könnte Ihnen auch gefallen