Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Daa Lab Manual Cse III I Sem

Download as pdf or txt
Download as pdf or txt
You are on page 1of 47

DEPARTMENT OF COMPUTER SCIENCE AND ENGINERING

DAA LAB MANUAL

List of Experiments

1. Write a java program to implement Quick sort algorithm for sorting a list of integers
in ascending order
2. Write a java program to implement Merge sort algorithm for sorting a list of integers
in ascending order.
i) Write a java program to implement the DFS algorithm for a graph.
ii) Write a. java program to implement the BFA algorithm for a graph.
3. Write a java programs to implement backtracking algorithm for the N-queens
problem.
4. Write a java program to implement the backtracking algorithm for the sum of subsets
problem.
5. Write a java program to implement the backtracking algorithm for the Hamiltonian
Circuits problem.
6. Write a java program to implement greedy algorithm for job sequencing with
deadlines.
7. Write a java program to implement Dijkstra’s algorithm for the Single source shortest
path problem.
8. Write a java program that implements Prim’s algorithm to generate minimum cost
spanning tree.
9. Write a java program that implements Kruskal’s algorithm to generate minimum cost
spanning tree
10. Write a java program to implement Floyd’s algorithm for the all pairs shortest path
problem.
11. Write a java program to implement Dynamic Programming algorithm for the 0/1
Knapsack problem.
12. Write a java program to implement Dynamic Programming algorithm for the Optimal
Binary Search Tree Problem.
PROGRAM-1

1. Write a java program to implement Quick sort algorithm for sorting a list of integers
in ascending order

public class QuickSortAscendingOrderDemo


{
public static void main(String args[])
{
//Numbers which need to be sorted
intnumbers[] = {23,5,23,1,7,12,3,34,0,-2,4,2,1222,2,0};

//Displaying the numbers before sorting


System.out.print("Before sorting, numbers are ");
for(inti = 0; i<numbers.length; i++)
{
System.out.print(numbers[i]+" ");
}
System.out.println();

//Sorting in ascending order using bubble sort


quickSortInAscendingOrder(numbers,0,numbers.length-1);

//Displaying the numbers after sorting


System.out.print("Before sorting, numbers are ");
for(inti = 0; i<numbers.length; i++)
{
System.out.print(numbers[i]+" ");
}

}
//This method sorts the input array in ascecnding order using quick sort
static void quickSortInAscendingOrder (int[] numbers, int low, int high)
{

inti=low;
int j=high;
int temp;
int middle=numbers[(low+high)/2];

while (i<j)
{
while (numbers[i]<middle)
{
i++;
}
while (numbers[j]>middle)
{
j--;
}
if (i<=j)
{
temp=numbers[i];
numbers[i]=numbers[j];
numbers[j]=temp;
i++;
j--;
}
}

if (low<j)
{
quickSortInAscendingOrder(numbers, low, j);
}
if (i<high)
{
quickSortInAscendingOrder(numbers, i, high);
}
}
}

Output:

Before sorting, numbers are 23 5 23 1 7 12 3 34 0 -2 4 2 1222 2 0


Before sorting, numbers are -2 0 0 1 2 2 3 4 5 7 12 23 23 34 1222
PROGRAM-2

2. Write a java program to implement Merge sort algorithm for sorting a list of integers
in ascending order.

public class MyMergeSort {

private int[] array;


private int[] tempMergArr;
private int length;

public static void main(String a[]){

int[] inputArr = {45,23,11,89,77,98,4,28,65,43};


MyMergeSort mms = new MyMergeSort();
mms.sort(inputArr);
for(int i:inputArr){
System.out.print(i);
System.out.print(" ");
}
}

public void sort(intinputArr[]) {


this.array = inputArr;
this.length = inputArr.length;
this.tempMergArr = new int[length];
doMergeSort(0, length - 1);
}

private void doMergeSort(intlowerIndex, inthigherIndex) {

if (lowerIndex<higherIndex) {
int middle = lowerIndex + (higherIndex - lowerIndex) / 2;
// Below step sorts the left side of the array
doMergeSort(lowerIndex, middle);
// Below step sorts the right side of the array
doMergeSort(middle + 1, higherIndex);
// Now merge both sides
mergeParts(lowerIndex, middle, higherIndex);
}
}

private void mergeParts(intlowerIndex, int middle, inthigherIndex) {


for (inti = lowerIndex; i<= higherIndex; i++) {
tempMergArr[i] = array[i];
}
inti = lowerIndex;
int j = middle + 1;
int k = lowerIndex;
while (i<= middle && j <= higherIndex) {
if (tempMergArr[i] <= tempMergArr[j]) {array[k] = tempMergArr[i];
i++;
} else {
array[k] = tempMergArr[j];
j++;
}
k++;
}
while (i<= middle) {
array[k] = tempMergArr[i];
k++;
i++;
}

}
}

Output:
4 11 23 28 43 45 65 77 89 98
i) Write a java program to implement the dfs algorithm for a graph.

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class DepthFirstSearchExampleNeighbourList


{

static class Node


{
int data;
boolean visited;
List<Node>neighbours;

Node(int data)
{
this.data=data;
this.neighbours=new ArrayList<>();

}
public void addneighbours(Node neighbourNode)
{
this.neighbours.add(neighbourNode);
}
public List<Node>getNeighbours() {
return neighbours;
}
public void setNeighbours(List<Node>neighbours) {
this.neighbours = neighbours;
}
}

// Recursive DFS
public voiddfs(Node node)
{
System.out.print(node.data + " ");
List<Node>neighbours=node.getNeighbours();
node.visited=true;
for (inti = 0; i<neighbours.size(); i++) {
Node n=neighbours.get(i);
if(n!=null && !n.visited){
dfs(n);
}
}
}
// Iterative DFS using stack
public voiddfsUsingStack(Node node)
{
Stack<Node> stack=new Stack<Node>();
stack.add(node);
node.visited=true;
while (!stack.isEmpty())
{
Node element=stack.pop();
System.out.print(element.data + " ");

List<Node>neighbours=element.getNeighbours();
for (inti = 0; i<neighbours.size(); i++) {
Node n=neighbours.get(i);
if(n!=null && !n.visited)
{
stack.add(n);
n.visited=true;

}
}
}
}

public static void main(String arg[])


{

Node node40 =new Node(40);


Node node10 =new Node(10);
Node node20 =new Node(20);
Node node30 =new Node(30);
Node node60 =new Node(60);
Node node50 =new Node(50);
Node node70 =new Node(70);

node40.addneighbours(node10);
node40.addneighbours(node20);
node10.addneighbours(node30);
node20.addneighbours(node10);
node20.addneighbours(node30);
node20.addneighbours(node60);
node20.addneighbours(node50);
node30.addneighbours(node60);
node60.addneighbours(node70);
node50.addneighbours(node70);

DepthFirstSearchExampleNeighbourListdfsExample = new
DepthFirstSearchExampleNeighbourList();
System.out.println("The DFS traversal of the graph using stack ");
dfsExample.dfsUsingStack(node40);
System.out.println();
// Resetting the visited flag for nodes
node40.visited=false;
node10.visited=false;
node20.visited=false;
node30.visited=false;
node60.visited=false;
node50.visited=false;
node70.visited=false;

System.out.println("The DFS traversal of the graph using recursion ");


dfsExample.dfs(node40);
}
}

Output:

The DFS traversal of the graph using stack


40 20 50 70 60 30 10
The DFS traversal of the graph using recursion
40 10 30 60 70 20 50
ii) Write a. java program to implement the bfs algorithm for a graph.

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class BreadthFirstSearchExampleNeighbourList


{

private Queue<Node> queue;


static ArrayList<Node> nodes=new ArrayList<Node>();
static class Node
{
int data;
boolean visited;
List<Node>neighbours;

Node(int data)
{
this.data=data;
this.neighbours=new ArrayList<>();

}
public void addneighbours(Node neighbourNode)
{
this.neighbours.add(neighbourNode);
}
public List<Node>getNeighbours() {
return neighbours;
}
public void setNeighbours(List<Node>neighbours) {
this.neighbours = neighbours;
}
}

public BreadthFirstSearchExampleNeighbourList()
{
queue = new LinkedList<Node>();
}
public void bfs(Node node)
{
queue.add(node);
node.visited=true;
while (!queue.isEmpty())
{

Node element=queue.remove();
System.out.print(element.data + "\t");
List<Node>neighbours=element.getNeighbours();
for (inti = 0; i<neighbours.size(); i++) {
Node n=neighbours.get(i);
if(n!=null && !n.visited)
{
queue.add(n);
n.visited=true;

}
}

}
}

public static void main(String arg[])


{

Node node40 =new Node(40);


Node node10 =new Node(10);
Node node20 =new Node(20);
Node node30 =new Node(30);
Node node60 =new Node(60);
Node node50 =new Node(50);
Node node70 =new Node(70);
node40.addneighbours(node10);
node40.addneighbours(node20);
node10.addneighbours(node30);
node20.addneighbours(node10);
node20.addneighbours(node30);
node20.addneighbours(node60);
node20.addneighbours(node50);
node30.addneighbours(node60);
node60.addneighbours(node70);
node50.addneighbours(node70);
System.out.println("The BFS traversal of the graph is ");
BreadthFirstSearchExampleNeighbourList Example = new BreadthFirstSearchExampleNeighbourList();
bfsExample.bfs(node40);

}
}

OUTPUT:

The BFS traversal of the graph is


40 10 20 30 60 50 70
PROGRAM-3

3. Write a java programs to implement backtracking algorithm for the N-queens


problem.
public class NQueens2DArray {
public static void main(String[] args) {
placeQueens(4); // Lets take example of 4*4
}
private static void placeQueens(intgridSize){

//If Grid is 1*1 or 2*2 or 3*3 then solution is not possible as,
//In 1*1 or 2*2 grid, Queen placed in 1st row at any position will attack queen placed at all the
positions in row 2.
//In 3*3 grid, Queen placed in 1st row and 2nd row for all combinations position will attack
queen placed at all the positions in row 3.
if(gridSize<4){
System.out.println("No Solution available");
}else{
int[][] board = new int[gridSize][gridSize];
placeAllQueens(board, 0);
printBoard(board);
}
}
private static booleanplaceAllQueens(int board[][], int row)
{
if(row>=board.length){
return true;
}
booleanisAllQueensPlaced = false;
for (int j = 0; j <board.length; j++)
{
if(isSafe(board, row, j)){
board[row][j] = 1;
isAllQueensPlaced = placeAllQueens(board, row+1);
}
if(isAllQueensPlaced)
{
break;
}
else
{
board[row][j] = 0;
}
}
return isAllQueensPlaced;
}

private static booleanisSafe(int board[][], int row, int col){

//Check Left Upper Diagonal


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

//Check Right Upper Diagonal


for (inti = row-1, j = col+1; i>= 0 && j <board.length; i--, j++) {
if(board[i][j] == 1){
return false;
}
}

//Check in same Column


for (inti = row-1; i>= 0; i--) {
if(board[i][col] == 1){
return false;
}
}

return true;
}

private static void printBoard(int[][] board){


for (int row = 0; row <board.length; row++) {
for (int col = 0; col <board.length; col++) {
if(board[row][col] == 1){
System.out.print("Q ");
}else{
System.out.print("_ ");
}
}
System.out.println();
}
System.out.println("");
}

}
Output:

_Q__
___Q
Q___
__Q_
PROGRAM-4

4. Write a java program to implement the backtracking algorithm for the sum of subsets
problem.

import java.util.Scanner;
public class Subset
{
static int c=0;
public static void main(String[] args)
{
int w[]=new int[10];
int n, d, i, sum=0;
int x[]=new int[10];
Scannerin=new Scanner(System.in);
System.out.println("********** SUBSET PROBLEM ************");
System.out.println("Enter the number of elements: ");
n=in.nextInt();
System.out.println("Enter the elements in increasing order");
for(i=0;i<n;i++)
w[i]=in.nextInt();
System.out.println("Enter the value of d: ");
d=in.nextInt();
for(i=0;i<n;i++)
sum=sum+w[i];
System.out.println("SUM ="+sum);
if(sum < d || w[0] > d){
System.out.println("Subset is not possible ! ");
System.exit(0);
}
subset(0,0,sum,x,w,d);
if(c==0)
System.out.println("Subset is not possible ! ");
System.out.println("\n********** ********* *************");
}
static void subset(int cs, int k, int r,int x[],int w[],int d)
{
x[k] = 1;
if(cs+w[k] == d)
{
c++;
System.out.print("\nSolution "+c+" is {");
for(int i=0;i<=k;i++)
if(x[i] == 1)
{
System.out.print(w[i]+" ");
}
System.out.print("}");
}
else if((cs + w[k] + w[k+1]) <= d)
subset(cs + w[k], k+1, r-w[k],x,w,d);
if((cs + r -w[k]) >=d && (cs + w[k+1]) <= d)
{
x[k] = 0;
subset(cs, k+1, r-w[k],x,w,d);
}
}
}
Output:
********** SUBSET PROBLEM ************
Enter the number of elements:5

Enter the elements in increasing order


12368
Enter the value of d:
9
SUM =20
Solution 1 is {1 2 6 }
Solution 2 is {1 8 }
Solution 3 is {3 6 }
PROGRAM-5
5. Write a java program to implement the backtracking algorithm for the Hamiltonian
Circuits problem.
import java.io.*;
public class Hamiltonian
{
static boolean found = false;
public static void main(String args[]) throws IOException
{
DataInputStream in=new DataInputStream(System.in);
System.out.println(“\t\t\t\tHamiltonian Cycle”);
System.out.print(“\nEnter the number of the vertices: “);int
n = Integer.parseInt(in.readLine());
int G[][] =new int[n+1][n+1];
int x[] =new int[n+1];
System.out.print(“\nIf edge between the following vertices enter 1 else 0:\n”);
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
{
if((i!=j)&&(i<j))
{
System.out.print(i+” and “+j+”: “); G[j][i]=G[i][j]
= Integer.parseInt(in.readLine());
}
if(i==j)
G[i][j]=0;
}
for(int i=1;i<=n;i++)
x[i] = 0;
x[1] = 1;
System.out.println(“\nSolution:”);

Hamiltonian (2,G,x,n);
if (found == false)
System.out.println(“No Solution possible!”);
}
static void Hamiltonian(int k,int G[][],int x[],int n)
{
while(true)
{
NextValue(k,G,x,n);
if(x[k] == 0)
return;if(k == n)
{
for(int i=1; i<=k;i++)
System.out.print(x[i]+” “);
System.out.println();
found= true;
return;
}
else
Hamiltonian(k+1,G,x,n);
}
}
static void NextValue(int k,int G[][],int x[],int n)
{
while(true)
{
x[k] = (x[k]+1)%(n+1);
if(x[k] == 0)
return;
if(G[x[k-1]][x[k]] !=0)
{
int j;
for(j = 1; j<k; j++)
if(x[k] == x[j])
break;
if(j==k)
if( (k<n) || ( (k==n) && G[x[n]][x[1]] != 0 ) )
return;
}
}
}
}

OUTPUT
Hamiltonian Cycle

Enter the number of the vertices: 4

If edge between the following vertices enter 1 else 0:1


and 2: 1
1 and 3: 1
1 and 4: 1
2 and 3: 1
3 and 4: 0
2 and 4: 1
Solution:
1234
1432

Solution 2 is {1 8 }

Solution 3 is {3 6 }
PROGRAM-6

6. Write a java program to implement greedy algorithm for job sequencing with deadlines.

import java.util.*;
class job
{
int p; // ............. for profit of a job
int d; // ............. for deadline of a job
int v; // ............ for checking if that job has been selected
job()
{
p=0;
d=0;
v=0;
}
job(int x,int y,int z) // parameterised constructor
{
p=x;
d=y;
v=z;
}
}
class js
{
static int n;
static int out(job jb[],int x)
{
for(int i=0;i<n;++i)if(job[i].p==x)
return i;
return 0;
}
public static void main(String args[])
{
Scanner scr=new Scanner(System.in);
System.out.println("Enter the number of jobs");
n=scr.nextInt();
int max=0; // this is to find the maximum deadline
job jb[]=new job[n];
for(int i=0;i<n;++i)
{
System.out.println("Enter profit and deadline(p d)");
int p=scr.nextInt();int d=scr.nextInt();if(max<d)
max=d; // assign maximum value of deadline to "max" variable
jb[i]=new job(p,d,0); //zero as third parameter to mark that initially it is unvisited
}
//accepted jobs from user
for(int i=0;i<=n-2;++i)
{
for(int j=i;j<=n-1;++j)
{
if(jb[i].d>jb[j].d)
{
job temp=jb[i];
jb[i]=jb[j];
jb[j]=temp;
}
}
}
// sorting process ends
System.out.println("The jobs are as follows ");
for(int i=0;i<n;++i)
System.out.println("Job "+i+" Profit = "+jb[i].p+" Deadline = "+jb[i].d);
// jobs displayed to the user
int count;
int hold[]=new int[max];
for(int i=0;i<max;++i)
hold[i]=0;
for(int i=0;i<n;++i)
{
count=0;
for(int j=0;j<n;++j)
{
if(count<jb[j].d && jb[j].v==0 && count<max && jb[j].p>hold[count])
{
int ch=0;
if(hold[count]!=0)
{
ch=out(jb,hold[count]);
jb[ch].v=0;
}
hold[count]=jb[j].p;
jb[j].v=1;
++count;
}
}
}
int profit=0;
for(int
i=0;i<max;++i)
profit+=hold[i];
System.out.println("The maximum profit is "+profit);
}
}
OUTPUT

Enter the number of jobs


4
Enter profit and deadline(p d)
70 2
Enter profit and deadline(p d)
12 1
Enter profit and deadline(p d)
18 2
Enter profit and deadline(p d)
35 1
The jobs are as follows
Job 0 Profit = 12 Deadline = 1
Job 1 Profit = 35 Deadline = 1
Job 2 Profit = 18 Deadline = 2
Job 3 Profit = 70 Deadline =

2The maximum profit is 105


PROGRAM-7

7. Write a java program to implement Dijkstra’s algorithm for the Single source
shortest path problem.

import java.util.Scanner;

public class Dijkstras {

public static void main(String[] args)

int i, j;

int dist[]=new int[10], visited[]=new int[10];

int cost[][]=new int[10][10], path[]=new int[10];

Scanner in = new Scanner(System.in);

System.out.println("**** DIJKSTRA'S ALGORITHM ******");

System.out.println("Enter the number of nodes: ");

int n= in.nextInt();

System.out.println("Enter the cost matrix");

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

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

cost[i][j] = in.nextInt();

System.out.println("The entered cost matrix is");

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

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

System.out.print(cost[i][j]+"\t");

}
System.out.println();

}
System.out.println("Enter the source vertex: ");

int sv = in.nextInt();

dij(cost,dist,sv,n,path,visited);

printpath(sv,n,dist,path,visited );

System.out.println("\n********* *************** *********");

static void dij(int cost[][],int dist[],int sv,int n,int path[],int visited[])

int count = 2,min,v=0;

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

visited[i]=0;

dist[i] = cost[sv][i];

if(cost[sv][i] == 999)

path[i] = 0;

else

path[i] = sv;

visited[sv]=1;

while(count<=n)

min = 999;

for(int w=1; w<=n; w++)


if((dist[w]< min) && (visited[w]==0))
{
min = dist[w];

v = w;

}
visited[v] = 1;

count++;

for(int w=1; w<=n; w++)

if((dist[w]) >(dist[v] + cost[v][w]))

dist[w] = dist[v] + cost[v][w];

path[w] = v;

static void printpath(int sv,int n,int dist[],int path[],int visited[])

for(int w=1; w<=n; w++)

if(visited[w] == 1 && w != sv)

System.out.println("The shortest distance between ");

System.out.println(sv+"-> ="+w+" is :"+ dist[w]);int t=path[w];

System.out.println("The path is:");System.out.print(" "+w);

while(t != sv)
{
System.out.print("<-->"+t);

t=path[t];

}
System.out.print("<-->"+sv);

OUTPUT

Enter the number of nodes:

Enter the cost matrix

0 5 0 999

5 0 1 999

999 1 999 2

999 999 5 0

The entered cost matrix is

0 5 0 999

5 0 1 999

999 1 999 2
999 999 5 0

Enter the source vertex:

The shortest distance between

1-> =2 is :1

The path is:

2<-→3<-→1

The shortest distance between1-> =3 is :0


PROGRAM-8

8. Write a java program that implements Prim’s algorithm to generate minimum


cost spanning tree.

import java.util.Scanner;

public class PRIM

public static void main(String[] args)

int cost[][]=new int[10][10];

int i, j, mincost = 0;

Scanner in = new Scanner(System.in);

System.out.println("********* PRIMS ALGORITHM *********");

System.out.println("Enter the number of nodes");

int n = in.nextInt();

System.out.println("Enter the cost matrix");

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

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

cost[i][j] = in.nextInt();

System.out.println("The entered cost matrix is");

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

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

{System.out.print(cost[i][j]+"\t");

}
System.out.println();

System.out.println("Minimum Spanning Tree Edges and costs are");

mincost=prims(cost,n,mincost);

System.out.print("The minimum spanning tree cost is:");

System.out.print(+mincost);

static int prims(int cost[][],int n,int mincost)

int nearV[]=new int[10],t[][]=new int[10][3],u = 0,i,j,k;

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

nearV[i]=1;

nearV[1]=0;

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

int min=999;

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

if(nearV[j]!=0 && cost[j][nearV[j]]<min)

min=cost[j][nearV[j]];

u=j;

}
}

t[i][1] = u;
t[i][2] = nearV[u];
mincost += min;

nearV[u] = 0;

for(k=1; k<=n; k++){

if(nearV[k] != 0 && cost[k][nearV[k]] > cost[k][u])

nearV[k] = u;

System.out.print(i+") Minimum edge is ("+t[i][1]);

System.out.println(","+t[i][2]+") and its cost is :"+min);

return mincost;

Output:

********* PRIMS ALGORITHM *********

Enter the number of nodes

3
Enter the cost matrix

999

0
1

999

0
The entered cost matrix is

0 2 999

2 0 1

999 1 0

Minimum Spanning Tree Edges and costs are

1) Minimum edge is (2,1) and its cost is :2

2) Minimum edge is (3,2) and its cost is :1

The minimum spanning tree cost is:3


PROGRAM-9

9. Write a java program that implements Kruskal’s algorithm to generate minimum


cost spanning tree
import java.util.Scanner;
public class KRUSKAL
{
public static void main(String[] args)
{
int cost[][]=new
int[10][10];int i,
j,mincost=0;
Scanner in = new Scanner(System.in);
System.out.println("********* KRUSKAL'S ALGORITHM
*******");System.out.println("Enter the number of nodes: ");
int n = in.nextInt();
System.out.println("Enter the cost matrix");
for(i=1;i<=n;i++){
for(j=1;j<=n;j++){
cost[i][j] =
in.nextInt();
}
}
System.out.println("The entered cost matrix is");
for(i=1;i<=n;i++){
for(j=1;j<=n;j++){
System.out.print(cost[i][j]+"\t");
}
System.out.println();
}
mincost=kruskals(n,mincost,cost);
System.out.println("The minimum spanning tree cost is:");
System.out.println(mincost);
}
static int kruskals(int n,int mincost,int cost[][] )
{
int ne =
1,a=0,u=0,b=0,v=0,min;int
parent[]=new int[10]; while(ne
< n){
min=999;
for(int i=1; i<=n; i++)
{
for(int j=1; j<=n; j++)
{
if(cost[i][j] < min){
min =
cost[i][j];
a=u=i;
b=v=j;
}
}
}
while(parent[u]>0)
u = parent[u];
while(parent[v]>0)
v = parent[v];
if(u != v)
{
System.out.print((ne++)+">minimum edge is :");
System.out.println("("+a+","+b+") and its cost is:"+min);
mincost += min;

parent[v] =u;
}
cost[a][b] = cost[b][a] = 999;
}
return mincost;
}
}
Output:
********* KRUSKAL'S ALGORITHM
*******Enter the number of nodes:
3
Enter the cost matrix
0
2
6
2
0
2
6
2
0
The entered cost matrix is

0 2 6
2 0 2
6 2 0
1>minimum edge is :(1,2) and its cost
is:22>minimum edge is :(2,3) and its cost
is: 2
PROGRAM-10

10. Write a java program to implement Floyd’s algorithm for the all pairs
shortest path problem

import java.util.Scanner;

class Floyd {

public static void main(String[] args)

int a[][]=new int[10][10];

int i, j;

Scanner in = new Scanner(System.in);

System.out.println("***********FLOYD'SALGORITHM**********");

System.out.println("Enter the number of vertices: ");

int n = in.nextInt();

System.out.println("Enter the adjacency matrix");

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

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

a[i][j] = in.nextInt();

System.out.println("Entered adjacency matrix is: ");

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

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

System.out.print(a[i][j]+"\t");

}
System.out.println();

}
floyd(a,n);

System.out.println("All pair shortest path matrix:");

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

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

System.out.print(a[i][j]+"\t");

System.out.println();

static void floyd(int a[][],int n)

for (int k=1; k<=n; k++)

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

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

a[i][j] = min(a[i][j], a[i][k] + a[k][j]);

static int min(int a,int b)

if(a>b)

return b;

else

return a;

}
Output:

***********FLOYD'SALGORITHM**********

Enter the number of vertices:

Enter the adjacency matrix

999

999

33

3
Entered adjacency matrix is:

0 1 3 1

2 0 5 999

4 7 999 1

33 2 1 3

All pair shortest path matrix:

0 1 2 1

2 0 4 3

4 3 2 1

4 2 1 2
PROGRAM-11

11. Write a java program to implement Dynamic Programming algorithm for the 0/1
Knapsack problem.
import java.util.Scanner;
public class Knapsack6a
{
static final int MAX = 20; // max. no. of
objectsstatic int w[]; // weights 0 to n-1
static int p[]; // profits 0 to n-1
static int n;
// no. of objects
static int M;
// capacity of Knapsack
static int V[][];
// DP solution process -table
static int Keep[][]; // to get objects in optimal solution
public static void main(String args[])
{
w = new
int[MAX];p = new
int[MAX];
V = new int [MAX][MAX];
Keep = new
int[MAX][MAX];int
optsoln;
ReadObjects();
for (int i = 0; i <= M;
i++)V[0][i] = 0;
for (int i = 0; i <= n;
i++)V[i][0] = 0;
optsoln = Knapsack();
System.out.println("Optimal solution = " + optsoln);
}
static int Knapsack()
{
int r; // remaining Knapsack capacity
for (int i = 1; i <= n; i++)
for (int j = 0; j <= M; j++)
if ((w[i] <= j) && (p[i] + V[i -1][j -w[i]] > V[i -1][j]))
{
V[i][j] = p[i] + V[i -1][j -w[i]];
Keep[i][j] = 1;
}
else
{
V[i][j] = V[i -1][j];
Keep[i][j] = 0;
}
// Find the objects included in the Knapsack
r = M;
System.out.println("Items = ");
for (int i = n; i > 0; i--) // start from
Keep[n,M]if (Keep[i][r] == 1)
{
System.out.println(i + "
");r = r -w[i];
}
System.out.println();
return V[n][M];
}
static void ReadObjects()
{
Scanner scanner = new Scanner(System.in);
System.out.println("Knapsack Problem -Dynamic Programming Solution: ");
System.out.println("Enter the max capacity of knapsack: ");
M = scanner.nextInt();
System.out.println("Enter number of objects: ");
n = scanner.nextInt();
System.out.println("Enter Weights: ");
for (int i = 1; i <= n; i++)
w[i] = scanner.nextInt();
System.out.println("Enter Profits: ");
for (int i = 1; i <= n; i++)
p[i] = scanner.nextInt();
scanner.close();
}
}
Output:
6)b. Implement in Java, the 0/1 Knapsack problem using Greedy method.
import java.util.Scanner;
import java.util.Scanner;

public class KnapsackDynamicProg


{

static int max(int a, int b)


{
return (a > b)? a : b;
}
static int knapSack(int W, int wt[], int val[], int n)
{
int i, w;
int [][]K = new int[n+1][W+1];

// Build table K[][] in bottom up mannerfor


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

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


{

if (i==0 || w==0)
K[i][w] = 0;
else if (wt[i-1] <= w)
K[i][w] = max(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];
}

public static void main(String args[])


{

Scanner sc = new Scanner(System.in);


System.out.println("Enter the number of items: ");
int n = sc.nextInt();

System.out.println("Enter the items weights: ");


int []wt = new int[n];
for(int i=0; i<n; i++)
wt[i] = sc.nextInt();
System.out.println("Enter the items values: ");
int []val = new int[n];
for(int i=0; i<n; i++)
val[i] = sc.nextInt();

System.out.println("Enter the maximum capacity: ");


int W = sc.nextInt();
System.out.println("The maximum value that can be put in a knapsack of capacity W is: " +
knapSack(W, wt, val, n));
sc.close();
}

Output:
PROGRAM-12

12. Write a java program to implement Dynamic Programming algorithm for


the Optimal Binary Search Tree Problem.

import java.io.*;
import
java.util.*;class
Optimal
{
public int p[];
public int q[];
public int a[];
public int
w[][];
public int c[][];
public int r[][];
public int n;
int front,rear,queue[];
public Optimal(int SIZE)
{
p=new int[SIZE];
q= new int[SIZE];
a=new int[SIZE];
w=new int[SIZE][SIZE];
c=new int[SIZE][SIZE];
r=new int[SIZE][SIZE];
queue=new int[SIZE];
front=rear=-1;
}

/* This function returns a value in the range r[i][j-1] to r[i+1][j] SO that the cost c[i][k-1] + c[k][j]
isminimum */

public int Min_Value(int i, int j)


{
int m,k=0;
int minimum = 32000;
for (m=r[i][j-1] ; m<=r[i+1][j] ; m++)
{
if ((c[i][m-1]+c[m][j]) < minimum)
{
minimum = c[i][m-1] +
c[m][j];k = m;
}
}
return k;
}
/* This function builds the table from all the given probabilities It basically computes C,r,W
values */
public void OBST()
{
int i, j, k, l, m;
for (i=0 ; i<n ;
i++)
{
// Initialize
w[i][i] =
q[i];
r[i][i] = c[i][i] = 0;
// Optimal trees with one
nodew[i][i+1] = q[i] + q[i+1]
+ p[i+1];r[i][i+1] = i+1;
c[i][i+1] = q[i] + q[i+1] + p[i+1];
}
w[n][n] = q[n];
r[n][n] = c[n][n] = 0;
// Find optimal trees with m
nodesfor (m=2 ; m<=n ; m++)
{
for (i=0 ; i<=n-m ; i++)
{
j = i+m;
w[i][j] = w[i][j-1] + p[j] +
q[j];k = Min_Value(i,j);
c[i][j] = w[i][j] + c[i][k-1] +
c[k][j];r[i][j] = k;
}
}
}

/*This function builds the tree from the tables made by the OBST function */

public void build_tree()


{
int i, j, k;
System.out.print("The Optimal Binary Search Tree For The Given Nodes Is \n");
System.out.print("\n The Root of this OBST is :: "+r[0][n]);
System.out.print("\n The Cost Of this OBST is :: "+c[0][n]);
System.out.print("\n\n\tNODE\tLEFT CHILD\tRIGHT CHILD");
System.out.println("\n ");

queue[++rear] =
0; queue[++rear]
= n; while(front
!= rear)
{
i=queue[++front];
j=queue[++front];
k= r[i][j];
System.out.print("\n);
if (r[i][k-1] != 0)
{
System.out.print(" "+r[i][k-]);
queue[++rear] = i;
queue[++rear] = k-1;
}
else
System.out.print(" -");
if(r[k][j] != 0)
{
System.out.print("
"+r[k][j]
);queue[++rear] = k;
queue[++rear] = j;
}
else
System.out.print(" -");
}
System.out.println("\n");
}
}
/* This is the main function
*/class OBSTDemo
{
public static void main (String[] args )throws IOException,NullPointerException
{
Optimal obj=new
Optimal(10);int i;
System.out.print("\n Optimal Binary Search Tree
\n");System.out.print("\n Enter the number of
nodes "); obj.n=getInt();
System.out.print("\n Enter the data as ... \n");
for (i=1;i<=obj.n;i++)
{
System.out.print("\n
a["+i+"]");obj.a[i]=getInt();
}
for (i=1 ; i<=obj.n ; i++)
{
System.out.println("p["+i+"]");
obj.p[i]=getInt();
}
for (i=0 ; i<=obj.n ; i++)
{
System.out.print("q["+i+"]");
obj.q[i]=getInt();
}
obj.OBST();
obj.build_tree();
}
public static String getString() throws IOException
{
InputStreamReader input = new InputStreamReader(System.in);
BufferedReader b = new BufferedReader(input);
String str = b.readLine();//reading the string from
consolereturn str;
}
public static char getChar() throws IOException
{
String str = getString();
return str.charAt(0);//reading first char of console string
}
public static int getInt() throws IOException
{
String str = getString();
return Integer.parseInt(str);//converting console string to numeric value
}
}
OUTPUT:
Optimal Binary Search Tree Enter the number of
nodes 4Enter the data as ....
a[1] 1
a[2] 2
a[3] 3
a[4] 4

p[1] 3
p[2] 3
p[3] 1
p[4] 1

q[0] 2
q[1] 3
q[2] 1
q[3] 1
q[4] 1

The Optimal Binary Search Tree For The Given Nodes Is ....

The Root of this OBST is :: 2


The Cost Of this OBSTis :: 32

You might also like