Professional Documents
Culture Documents
Dept. of Computer Science and Business Systems Master Lab Manual 2022 – 23
DEPARTMENT OF
COMPUTER SCIENCE AND BUSINESS
SYSTEMS
ACADEMIC YEAR 2022-23
Prepared By :
xxxxxxx, Assistant Professor CSB
Recursive Algorithm: This is one of the most interesting Algorithms as it calls itself with a
smaller value as inputs which it gets after solving for the current inputs. In simpler words, it’s
an Algorithm that calls itself repeatedly until the problem is solved. Problems such as the
Tower of Hanoi or DFS of a Graph can be easily solved by using these Algorithms.
Divide and Conquer: This is another effective way of solving many problems. In Divide and
Conquer algorithms, divide the algorithm into two parts; the first parts divide the problem on
hand into smaller sub problems of the same type. Then, in the second part, these smaller
problems are solved and then added together (combined) to produce the problem’s final
solution. Problems such as Binary Search, Quick Sort, and Merge Sort can be solved using
this technique.
Dynamic Programming: These algorithms work by remembering the results of the past run
and using them to find new results. In other words, a dynamic programming algorithm solves
complex problems by breaking them into multiple simple sub problems and then it solves
each of them once and then stores them for future use. Dynamic Programming is frequently
related to Optimization Problems. Problems such as Multistage Graphs, Optimal Binary
Search Tress can be solved using this technique.
Greedy Technique: This is used to solve the optimization problem. An optimization
problem is one in which there is a given a set of input values, which are required either to be
maximized or minimized (known as objective), i.e. some constraints or conditions. It always
makes the choice (greedy criteria) looks best at the moment, to optimize a given objective. It
doesn't always guarantee the optimal solution however it generally produces a solution that is
very close in value to the optimal. Problems such as Kruskal’s Minimum Spanning Tree
(MST), Prim's Minimal Spanning Tree, Dijkstra's Minimal Spanning Tree and Knapsack
Problem can be solved using this technique.
Brute Force Algorithm: This is one of the simplest algorithms in the concept. A brute force
algorithm blindly iterates all possible solutions to search one or more than one solution that
may solve a function. Think of brute force as using all possible combinations of numbers to
open a safe. Problems such as Selection Sort, convex hull can be solved using this technique.
Backtracking Algorithm: Backtracking is a technique to find a solution to a problem in an
incremental approach. It solves problems recursively and tries to solve a problem by solving
one piece of the problem at a time. If one of the solutions fails, we remove it and backtrack to
find another solution. In other words, a backtracking algorithm solves a sub problem, and if it
fails to solve the problem, it undoes the last step and starts again to find the solution to the
problem. N-Queens problem is one good example to see Backtracking algorithm in action.
Vignana Bharathi Institute of Technology Page 4
Design Analysis Of Algorithms
Dept. of Computer Science and Business Systems Master Lab Manual 2022 – 23
Branch and Bound: In Branch & Bound algorithm a given sub problem, which cannot be
bounded, has to be divided into at least two new restricted sub problems. Branch and Bound
algorithm are methods for global optimization in non-convex problems. Branch and Bound
algorithms can be slow, however in the worst case they require effort that grows
exponentially with problem size.
COURSE OBJECTIVE
To write programs in java to solve problems using divide and conquer strategy.
To write programs in java to solve problems using backtracking strategy.
To write programs in java to solve problems using greedy and dynamic programming
techniques.
PROGRAMME EDUCATIONAL OBJECTIVES (PEO)
Lifelong Learning: Graduates of CSB-VBIT, will recognize the importance of, and
P5 have the skills for, continued independent learning to become experts in their chosen
fields and to broaden their professional knowledge.
PROGRAMMEOUTCOMES (PO)
LAB INSTRUCTOINS
Students should report to the concerned lab as per the time table.
Students who turn up late to the labs will in no case be permitted to do the program
schedule for the day.
After completion of the program, certification of the concerned staff in-charge in the
observation book is necessary.
Student should bring a notebook of 100 pages and should enter the readings
/observations into the notebook while performing the experiment.
The record of observations along with the detailed experimental procedure of the
experiment in the immediate last session should be submitted and certified staff
member in-charge.
Not more than 3-students in a group are permitted to perform the experiment on the
set.
The group-wise division made in the beginning should be adhered to and no mix up
of students among different groups will be permitted.
1. Intel based desktop PC with minimum of 2.6GHz or faster processor with at least 1GB
RAM and 40 GB free disk space and LAN connected.
2. Operating System: Ubuntu.
3. Software: JAVA Compiler
Objective:
To learn the importance of designing an algorithm in an effective way by considering space
and time complexity
To learn divide and conquer strategy based algorithms
To learn greedy method based algorithms
To learn the dynamic programming design techniques
To develop Recursive backtracking algorithms
To learn graph search and network flow algorithms
System Requirements
1. Intel based desktop PC with minimum of 2.6GHz or faster processor with at least 1GB
RAM and 40 GB free disk space and LAN connected.
2. Operating System: Ubuntu.
3. Software: JAVA Compile
Program
Name Of The Program Page No.
No.
Write a java program to implement Merge Sort algorithm for sorting a list
1 of integers in ascending order. 10
Write a java program to implement Quick Sort algorithm for sorting a list
2 of integers in ascending order. 12
Write a java program to implement Floyd’s algorithm for the all pairs
11 shortest path problem. 40
INDEX
PROGRAM NO : 1.
AIM: Write A Java Program to implement Merge Sort algorithm for sorting a list of
integers in ascending order.
THEORY:
Merge Sort is a Divide and Conquer algorithm. It divides the input array into two
halves, calls itself for the two halves, and then merges the two sorted halves. The Merge()
function is used for merging two halves. The Mergesort() is a key process that sorts the
A[l..m] and A[m+1..r] into two sorted sub-arrays.
SOURCE CODE:
class Mergesort
{
void merge(int arr[], int l, int m, int r)
{
int n1 = m - l + 1;
int n2 = r - m;
int L[] = new int [n1];
int R[] = new int [n2];
for (int i=0; i<n1; ++i)
L[i] = arr[l + i];
for (int j=0; j<n2; ++j)
R[j] = arr[m + 1+ j];
int i = 0, j = 0;
int k = l;
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
}
while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}
while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}
}
void sort(int arr[], int l, int r)
{
if (l < r)
{
int m = (l+r)/2;
sort(arr, l, m);
sort(arr , m+1, r);
merge(arr, l, m, r);
}
}
static void printArray(int arr[])
{
int n = arr.length;
for (int i=0; i<n; ++i)
System.out.print(arr[i] + " ");
System.out.println();
}
public static void main(String args[])
{
int arr[] = {12, 11, 13, 5, 6, 7};
System.out.println("Given Array");
printArray(arr);
Mergesort ob = new Mergesort();
ob.sort(arr, 0, arr.length-1);
System.out.println("\nSorted array");
printArray(arr);
}
}
OUTPUT:
PROGRAM NO : 2
AIM: Write A Java Program to implement Quick Sort algorithm for sorting a list of integers
in ascending order.
THEORY:
Quick Sort is a Divide and Conquer algorithm. It picks an element as pivot and
partitions the given array around the picked pivot. There are many different versions of quick
Sort that pick pivot in different ways.
Always pick first element as pivot.
Always pick last element as pivot (implemented below)
Pick a random element as pivot.
Pick median as pivot.
The key process in quick Sort is partition ().Target of partition() is, given an array and
an element x of array as pivot, put x at its correct position in sorted array and put all smaller
elements (smaller than x) before x, and put all greater elements (greater than x) after x.
SOURCE CODE:
import java.util.Arrays;
public class QuickSortDemo{
public static void main(String args[]) {
int[] unsorted = {6, 5, 3, 1, 8, 7, 2, 4};
System.out.println("Unsorted array :" + Arrays.toString(unsorted));
QuickSort algorithm = new QuickSort();
algorithm.sort(unsorted);
System.out.println("Sorted array :" + Arrays.toString(unsorted));
}
}
class QuickSort {
private int input[];
private int length;
public void sort(int[] numbers) {
if (numbers == null || numbers.length == 0) {
return;
}
this.input = numbers;
length = numbers.length;
quickSort(0, length - 1);
}
private void quickSort(int low, int high) {
int i = low;
int j = high;
int pivot = input[low + (high - low) / 2];
while (i <= j) {
while (input[i] < pivot) {
i++;
}
while (input[j] > pivot) {
j--;
}
if (i <= j) {
swap(i, j);
i++;
j--;
}
}
if (low < j) {
quickSort(low, j);
}
if (i < high) {
quickSort(i, high);
}
}
private void swap(int i, int j) {
OUTPUT:
PROGRAM NO : 3.
AIM: Write A Java Program to implement Depth First Search(DFS) algorithm for a graph.
THEORY:
Depth First Search: A depth first search of a graph differs from a breadth first search in
that the exploration of a vertex v is suspended as soon as a new vertex is reached. At this time
the exploration of the new vertex u begins. When this new vertex has been explored, the
exploration of v continues. The search terminates when all reached vertices have been fully
explored. Depth-first search starts visiting vertices of a graph at an arbitrary vertex by
marking it as having been visited. On each iteration, the algorithm proceeds to an unvisited
vertex that is adjacent to the one it is currently in. This process continues until a vertex with
no adjacent unvisited vertices is encountered. At a dead end, the algorithm backs up one edge
to the vertex it came from and tries to continue visiting unvisited vertices from there. The
algorithm eventually halts after backing up to the starting vertex, with the latter being a dead
end.
SOURCE CODE:
import java.util.InputMismatchException;
import java.util.Scanner;
import java.util.Stack;
public class DFS
{
private Stack<Integer> stack;
public DFS()
{
stack = new Stack<Integer>();
}
public void dfs(int adjacency_matrix[][], int source)
{
int number_of_nodes = adjacency_matrix[source].length - 1;
int visited[] = new int[number_of_nodes + 1];
int element = source;
int i = source;
System.out.print(element + "\t");
visited[source] = 1;
stack.push(source);
while (!stack.isEmpty())
{
element = stack.peek();
i = element;
while (i <= number_of_nodes)
{
if (adjacency_matrix[element][i] == 1 && visited[i] == 0)
{
stack.push(i);
visited[i] = 1;
element = i;
i = 1;
System.out.print(element + "\t");
continue;
}
i++;
}
stack.pop();
}
}
public static void main(String...arg)
{
int number_of_nodes, source;
OUTPUT:
PROGRAM NO : 4
AIM: Write A Java Program to implement Breadth First Search(BFS) algorithm for a graph.
THEORY:
Breadth First Search: In breadth first search start at a vertex v and mark it as having
been reached (visited). The vertex v is at this time said to be unexplored. A vertex is said to
have been explored by an algorithm when the algorithm has visited all vertices adjacent from
it. All unvisited vertices adjacent from v are visited next. These are new unexplored vertices.
Vertex v has now been explored. The newly visited vertices haven't been explored and are
put onto the end of a list of unexplored vertices. The first vertex on this list is the next to be
explored. Exploration continues until no unexplored vertex is left. The list of unexplored
vertices operates as a queue and can be represented using any of the standard queue
representation. BFS explores graph moving across to all the neighbors of last visited vertex
traversals i.e., it proceeds in a concentric manner by visiting all the vertices that are adjacent
to a starting vertex, then all unvisited vertices two edges apart from it and so on, until all the
vertices in the same connected component as the starting vertex are visited. Instead of a stack,
BFS uses queue.
SOURCE CODE:
import java.util.InputMismatchException;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class BFS
{
private Queue<Integer> queue;
public BFS()
{
queue = new LinkedList<Integer>();
}
public void bfs(int adjacency_matrix[][], int source)
{
int number_of_nodes = adjacency_matrix[source].length - 1;
int[] visited = new int[number_of_nodes + 1];
int i, element;
visited[source] = 1;
queue.add(source);
while (!queue.isEmpty())
{
element = queue.remove();
i = element;
System.out.print(i + "\t");
while (i <= number_of_nodes)
{
if (adjacency_matrix[element][i] == 1 && visited[i] == 0)
{
queue.add(i);
visited[i] = 1;
}
i++;
}
}
}
public static void main(String... arg)
{
int number_no_nodes, source;
Scanner scanner = null;
try
{
System.out.println("Enter the number of nodes in the graph");
scanner = new Scanner(System.in);
number_no_nodes = scanner.nextInt();
int adjacency_matrix[][] = new int[number_no_nodes + 1][number_no_nodes + 1];
System.out.println("Enter the adjacency matrix");
for (int i = 1; i <= number_no_nodes; i++)
for (int j = 1; j <= number_no_nodes; j++)
adjacency_matrix[i][j] = scanner.nextInt();
System.out.println("Enter the source for the graph");
source = scanner.nextInt();
System.out.println("The BFS traversal of the graph is ");
BFS bfs = new BFS();
bfs.bfs(adjacency_matrix, source);
} catch (InputMismatchException inputMismatch)
{
System.out.println("Wrong Input Format");
}
scanner.close();
}
}
OUTPUT:
PROGRAM NO : 5
AIM: A Java Program to implement greedy algorithm for job sequencing with deadlines.
THEORY:
Given an array of jobs where every job has a deadline and associated profit if the job
is finished before the deadline. It is also given that every job takes single unit of time, so the
minimum possible deadline for any job is 1.
Source Code:
import java.util.*;
public class Job
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number of Jobs");
int n=sc.nextInt();
String a[]=new String[n];
int b[]=new int[n];
int c[]=new int[n];
for(int i=0;i<n;i++)
{
System.out.println("Enter the Jobs");
a[i]=sc.next();
System.out.println("Enter the Profit");
b[i]=sc.nextInt();
System.out.println("Enter the DeadLine");
c[i]=sc.nextInt();
}
System.out.println("--Arranged Order--");
System.out.print("Jobs: ");
for(int i=0;i<n;i++)
{
System.out.print(a[i]+" ");
}
System.out.println();
System.out.print("Profit: ");
for(int i=0;i<n;i++)
{
System.out.print(b[i]+" ");
}
System.out.println();
System.out.print("DeadLine:");
for(int i=0;i<n;i++)
{
System.out.print(c[i]+" ");
}
for(int i=0;i<n-1;i++)
{
for(int j=i+1;j<n;j++)
{
if(b[i]<b[j])
{
int temp=b[i];
b[i]=b[j];
b[j]=temp;
temp=c[i];
c[i]=c[j];
c[j]=temp;
String temp1=a[i];
a[i]=a[j];
a[j]=temp1;
}
}
}
System.out.println();
System.out.println("--Sorted Order--");
System.out.print("Jobs: ");
for(int i=0;i<n;i++)
{
System.out.print(a[i]+" ");
}
System.out.println();
System.out.print("Profit: ");
for(int i=0;i<n;i++)
{
System.out.print(b[i]+" ");
}
System.out.println();
System.out.print("DeadLine:");
for(int i=0;i<n;i++)
{
System.out.print(c[i]+" ");
}
System.out.println();
int max=c[0];
for(int i=0;i<n;i++)
{
if(c[i]>max)
{
max=c[i];
}
}
String x[]=new String[max];
int xx[]=new int[max];
int profit=0;
for(int i=0;i<n;i++)
{
int pp=c[i];
pp=pp-1;
if(x[pp]==null )
{
x[pp]=a[i];
profit+=b[i];
}
else
{
while(pp!=-1)
{
if(x[pp]==null)
{
x[pp]=a[i];
profit+=b[i];
break;
}
pp=pp-1;
}
}
}
for(int i=0;i<max;i++)
{
System.out.print("-->"+x[i]);
}
System.out.println();
System.out.print("Profit Earned"+profit);
}
}
OUTPUT:
PROGRAM NO : 6
AIM: Write A Java Program to implement Dijkstra’s algorithm for the Single Source
Shortest Path Problem.
THEORY:
Single Source Shortest Paths Problem: For a given vertex called the source in a
weighted connected graph, find the shortest paths to all its other vertices. Dijkstra’s algorithm
is the best known algorithm for the single source shortest paths problem. This algorithm is
applicable to graphs with nonnegative weights only and finds the shortest paths to a graph’s
vertices in order of their distance from a given source. It finds the shortest path from the
source to a vertex nearest to it, then to a second nearest, and so on. It is applicable to both
undirected and directed graphs.
Source Code:
import java.util.*;
public class Dijkstra
{
public int distance[] = new int[10];
public int cost[][] = new int[10][10];
public void calc(int n,int s)
{
int flag[] = new int[n+1];
int i,minpos=1,k,c,minimum;
for(i=1;i<=n;i++)
{
flag[i]=0;
this.distance[i]=this.cost[s][i];
}
c=2;
while(c<=n)
{
minimum=99;
for(k=1;k<=n;k++)
{
if(this.distance[k]<minimum && flag[k]!=1)
{
minimum=this.distance[i];
minpos=k;
}
}
flag[minpos]=1;
c++;
for(k=1;k<=n;k++)
{
if(this.distance[minpos]+this.cost[minpos][k] < this.distance[k] && flag[k]!=1 )
this.distance[k]=this.distance[minpos]+this.cost[minpos][k];
}
}
}
public static void main(String args[])
{
int nodes,source,i,j;
Scanner in = new Scanner(System.in);
System.out.println("Enter the Number of Nodes \n");
nodes = in.nextInt();
Dijkstra d = new Dijkstra();
System.out.println("Enter the Cost Matrix Weights: \n");
for(i=1;i<=nodes;i++)
for(j=1;j<=nodes;j++)
{
d.cost[i][j]=in.nextInt();
if(d.cost[i][j]==0)
d.cost[i][j]=999;
}
System.out.println("Enter the Source Vertex :\n");
source=in.nextInt();
d.calc(nodes,source);
System.out.println("The Shortest Path from Source \t"+source+"\t to all other vertices are : \
n");
for(i=1;i<=nodes;i++)
if(i!=source)
System.out.println("source :"+source+"\t destination :"+i+"\t MinCost is :"+d.distance[i]+"\
t");
}
}
OUTPUT:
PROGRAM NO : 7
AIM: Write A Java Program to implement Prims’s algorithm to generate minimum cost
spanning tree.
THEORY:
Prim’s algorithm finds the minimum spanning tree for a weighted connected graph
G=(V,E) to get an acyclic sub graph with |V|-1 edges for which the sum of edge weights is
the smallest. Consequently the algorithm constructs the minimum spanning tree as expanding
sub-trees. The initial sub tree in such a sequence consists of a single vertex selected
arbitrarily from the set V of the graph’s vertices. On each iteration, expand the current tree in
the greedy manner by simply attaching to it the nearest vertex not in that tree. The algorithm
stops after all the graph’s vertices have been included in the tree being constructed.
SOURCE CODE:
import java.util.InputMismatchException;
import java.util.Scanner;
public class Prims
{
private boolean unsettled[];
private boolean settled[];
private int numberofvertices;
private int adjacencyMatrix[][];
private int key[];
public static final int INFINITE = 999;
private int parent[];
public Prims(int numberofvertices)
{
this.numberofvertices = numberofvertices;
unsettled = new boolean[numberofvertices + 1];
settled = new boolean[numberofvertices + 1];
adjacencyMatrix = new int[numberofvertices + 1][numberofvertices + 1];
key = new int[numberofvertices + 1];
parent = new int[numberofvertices + 1];
}
public int getUnsettledCount(boolean unsettled[])
{
int count = 0;
for (int index = 0; index < unsettled.length; index++)
{
if (unsettled[index])
{
count++;
}
}
return count;
}
public void primsAlgorithm(int adjacencyMatrix[][])
{
int evaluationVertex;
for (int source = 1; source <= numberofvertices; source++)
{
for (int destination = 1; destination <= numberofvertices; destination++)
{
this.adjacencyMatrix[source][destination] = adjacencyMatrix[source]
[destination];
}
}
for (int index = 1; index <= numberofvertices; index++)
{
key[index] = INFINITE;
}
key[1] = 0;
unsettled[1] = true;
parent[1] = 1;
while (getUnsettledCount(unsettled) != 0)
{
evaluationVertex = getMimumKeyVertexFromUnsettled(unsettled);
unsettled[evaluationVertex] = false;
settled[evaluationVertex] = true;
evaluateNeighbours(evaluationVertex);
}
}
private int getMimumKeyVertexFromUnsettled(boolean[] unsettled2)
{
int min = Integer.MAX_VALUE;
int node = 0;
for (int vertex = 1; vertex <= numberofvertices; vertex++)
{
if (unsettled[vertex] == true && key[vertex] < min)
{
node = vertex;
min = key[vertex];
}
}
return node;
}
public void evaluateNeighbours(int evaluationVertex)
{
for (int destinationvertex = 1; destinationvertex <= numberofvertices;
destinationvertex++)
{
if (settled[destinationvertex] == false)
{
if (adjacencyMatrix[evaluationVertex][destinationvertex] != INFINITE)
{
if (adjacencyMatrix[evaluationVertex][destinationvertex] <
key[destinationvertex])
{
key[destinationvertex] = adjacencyMatrix[evaluationVertex]
[destinationvertex];
parent[destinationvertex] = evaluationVertex;
}
unsettled[destinationvertex] = true;
}
}
}
}
public void printMST()
{
System.out.println("SOURCE : DESTINATION = WEIGHT");
for (int vertex = 2; vertex <= numberofvertices; vertex++)
{
System.out.println(parent[vertex] + "\t:\t" + vertex +"\t=\t"+
adjacencyMatrix[parent[vertex]][vertex]);
}
}
public static void main(String... arg)
{
int adjacency_matrix[][];
int number_of_vertices;
Scanner scan = new Scanner(System.in);
try
{
System.out.println("Enter the number of vertices");
number_of_vertices = scan.nextInt();
adjacency_matrix = new int[number_of_vertices + 1][number_of_vertices + 1];
System.out.println("Enter the Weighted Matrix for the graph");
for (int i = 1; i <= number_of_vertices; i++)
{
for (int j = 1; j <= number_of_vertices; j++)
{
adjacency_matrix[i][j] = scan.nextInt();
if (i == j)
{
adjacency_matrix[i][j] = 0;
continue;
}
if (adjacency_matrix[i][j] == 0)
{
adjacency_matrix[i][j] = INFINITE;
}
}
}
Prims prims = new Prims(number_of_vertices);
prims.primsAlgorithm(adjacency_matrix);
prims.printMST();
} catch (InputMismatchException inputMismatch)
{
System.out.println("Wrong Input Format");
}
scan.close();
}
}
OUTPUT:
PROGRAM NO : 8
AIM: Write A Java Program to implement Kruskal’s algorithm to generate minimum cost
spanning tree.
THEORY:
SOURCE CODE:
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
import java.util.Stack;
public class KruskalAlgorithm
{
private List<Edge> edges;
private int numberOfVertices;
public static final int MAX_VALUE = 999;
private int visited[];
private int spanning_tree[][];
public KruskalAlgorithm(int numberOfVertices)
{
this.numberOfVertices = numberOfVertices;
edges = new LinkedList<Edge>();
visited = new int[this.numberOfVertices + 1];
spanning_tree = new int[numberOfVertices + 1][numberOfVertices + 1];
}
public void kruskalAlgorithm(int adjacencyMatrix[][])
{
boolean finished = false;
for (int source = 1; source <= numberOfVertices; source++)
{
for (int destination = 1; destination <= numberOfVertices; destination++)
{
if (adjacencyMatrix[source][destination] != MAX_VALUE && source != destination)
{
Edge edge = new Edge();
edge.sourcevertex = source;
edge.destinationvertex = destination;
edge.weight = adjacencyMatrix[source][destination];
adjacencyMatrix[destination][source] = MAX_VALUE;
edges.add(edge);
}
}
}
Collections.sort(edges, new EdgeComparator());
CheckCycle checkCycle = new CheckCycle();
for (Edge edge : edges)
{
spanning_tree[edge.sourcevertex][edge.destinationvertex] = edge.weight;
spanning_tree[edge.destinationvertex][edge.sourcevertex] = edge.weight;
if (checkCycle.checkCycle(spanning_tree, edge.sourcevertex))
{
spanning_tree[edge.sourcevertex][edge.destinationvertex] = 0;
spanning_tree[edge.destinationvertex][edge.sourcevertex] = 0;
edge.weight = -1;
continue;
}
visited[edge.sourcevertex] = 1;
visited[edge.destinationvertex] = 1;
for (int i = 0; i < visited.length; i++)
{
if (visited[i] == 0)
{
finished = false;
break;
} else
{
finished = true;
}
}
if (finished)
break;
}
System.out.println("The spanning tree is ");
for (int i = 1; i <= numberOfVertices; i++)
System.out.print("\t" + i);
System.out.println();
for (int source = 1; source <= numberOfVertices; source++)
{
System.out.print(source + "\t");
for (int destination = 1; destination <= numberOfVertices; destination++)
{
System.out.print(spanning_tree[source][destination] + "\t");
}
System.out.println();
}
}
public static void main(String... arg)
{
int adjacency_matrix[][];
int number_of_vertices;
Scanner scan = new Scanner(System.in);
System.out.println("Enter the number of vertices");
number_of_vertices = scan.nextInt();
adjacency_matrix = new int[number_of_vertices + 1][number_of_vertices + 1];
class CheckCycle
{
private Stack<Integer> stack;
private int adjacencyMatrix[][];
public CheckCycle()
{
}
i++;
}
stack.pop();
}
return cyclepresent;
}
OUTPUT:
PROGRAM NO : 9
AIM: Write a java program to implement Dynamic Programming algorithm for the 0/1
Knapsack problem.
THEORY:
Given n objects and a knapsack or bag. Object i has a weight wi and the knapsack has
a capacity m. If a fraction xi, 0 < 1, of object i is placed into the knapsack, then a profit of
pixi is earned. The objective is to obtain a filling of the knapsack that maximizes the total
profit earned. Since the knapsack capacity is m, the total required is the weight of all chosen
objects to be at most m.
Dynamic programming approach: To design a dynamic programming algorithm, derive a
recurrence relation that expresses a solution to an instance of the knapsack problem in terms
of solutions to its smaller sub instances. Consider an instance defined by the first i items,
1<=i<=n, with weights w1,…..,wi, values v1,……vi and knapsack capacity j, 1<=j<=W. Let
V [i,j] be the value of an optimal solution to this instance. Divide all the subsets in to two
categories: those that include the ith item and those that do not. 1) Among the subsets that do
not include the ith item, the value of an optimal subset is, V [i-1,j]. 2) Among the subsets that
do include the ith item , an optimal subset is made up of this item and an optimal subset of
the first i-1 items that fit into the knapsack of capacity j-wi. The value of such a an optimal
subset is vi + V[i-1,j-wi]. Thus, the value of an optimal solution among all feasible subsets of
the first I items is the maximum of these two values. The goal is to find v[n,W] , the maximal
value of subset of the n given items that fit into the knapsack of capacity W, and an optimal
subset itself.
SOURCE CODE:
import java.util.Scanner;
public class Zero_One_Knapsack
{
public void solve(int[] wt, int[] val, int W, int N)
{
int NEGATIVE_INFINITY = Integer.MIN_VALUE;
int[][] m = new int[N + 1][W + 1];
int[][] sol = new int[N + 1][W + 1];
for (int i = 1; i <= N; i++)
{
for (int j = 0; j <= W; j++)
{
int m1 = m[i - 1][j];
int m2 = NEGATIVE_INFINITY;
if (j >= wt[i])
m2 = m[i - 1][j - wt[i]] + val[i];
m[i][j] = Math.max(m1, m2);
sol[i][j] = m2 > m1 ? 1 : 0;
}
}
int[] selected = new int[N + 1];
for (int n = N, w = W; n > 0; n--)
{
if (sol[n][w] != 0)
{
selected[n] = 1;
w = w - wt[n];
}
else
selected[n] = 0;
}
System.out.print("\nItems with weight ");
for (int i = 1; i < N + 1; i++)
if (selected[i] == 1)
System.out.print(val[i] +" ");
System.out.println("are selected by knapsack algorithm.");
}
public static void main (String[] args)
{
Scanner scan = new Scanner(System.in);
Zero_One_Knapsack ks = new Zero_One_Knapsack();
System.out.println("Enter number of elements ");
int n = scan.nextInt();
int[] wt = new int[n + 1];
int[] val = new int[n + 1];
System.out.println("Enter weight for "+ n +" elements");
for (int i = 1; i <= n; i++)
wt[i] = scan.nextInt();
System.out.println("Enter value for "+ n +" elements");
for (int i = 1; i <= n; i++)
val[i] = scan.nextInt();
System.out.println("Enter knapsack weight ");
int W = scan.nextInt();
ks.solve(wt, val, W, n);
scan.close();
OUTPUT:
PROGRAM NO : 10
AIM: Write a java program to implement Dynamic Programming algorithm for the Optimal
Binary Search Tree problem.
THEORY:
optimal binary search tree (Optimal BST), sometimes called a weight-balanced binary
tree, [1] is a binary search tree which provides the smallest possible search time (or expected
search time) for a given sequence of accesses (or access probabilities). Optimal BSTs are
generally divided into two types: static and dynamic. In the static optimality problem, the tree
cannot be modified after it has been constructed. In this case, there exists some particular
layout of the nodes of the tree which provides the smallest expected search time for the given
access probabilities. Various algorithms exist to construct or approximate the statically
optimal tree given the information on the access probabilities of the elements.
SOURCE CODE:
import java.util.*;
public class Main {
static final int MAX = 1000;
static int cost[][] = new int[MAX][MAX];
static int Sum(int freq[], int i, int j)
{
int s = 0;
for (int k = i; k <= j; k++)
s += freq[k];
return s;
}
static int optCost_memoized(int freq[], int i, int j)
{
if (i < 0 || j < 0)
return 0;
if (cost[i][j] != 0)
return cost[i][j];
int fsum = Sum(freq, i, j);
int Min = Integer.MAX_VALUE;
for (int r = i; r <= j; r++) {
int c = optCost_memoized(freq, i, r - 1)
+ optCost_memoized(freq, r + 1, j)
+ fsum;
if (c < Min) {
Min = c;
cost[i][j] = c;
}
}
return cost[i][j];
}
static int optimalSearchTree(int keys[], int freq[],
int n)
{
return optCost_memoized(freq, 0, n - 1);
}
}
}
OUTPUT:
PROGRAM NO : 11
AIM: Write a java program to implement Floyd’s algorithm for the all pairs shortest path
problem.
THEORY:
Floyd’s algorithm is applicable to both directed and undirected graphs provided that they do
not contain a cycle of negative length. It is convenient to record the lengths of shortest path in
an n- by- n matrix D called the distance matrix. The element dij in the ith row and jth column
of matrix indicates the length of shortest path from the ith vertex to jth vertex (1≤ i, j ≤ n). The
element in the ith row and jth column of the current matrix D (k-1)is replaced by the sum of
elements in the same row i and kth column and in the same column j and the kth column if
and only if the latter sum is smaller than its current value.
SOURCE CODE:
import java.util.Scanner;
public class FloydWarshall
{
private int distancematrix[][];
private int numberofvertices;
public static final int INFINITY = 999;
public FloydWarshall(int numberofvertices)
{
distancematrix = new int[numberofvertices + 1][numberofvertices + 1];
this.numberofvertices = numberofvertices;
}
public void floydwarshall(int adjacencymatrix[][])
{
for (int source = 1; source <= numberofvertices; source++)
{
for (int destination = 1; destination <= numberofvertices; destination++)
{
distancematrix[source][destination] = adjacencymatrix[source][destination];
}
}
for (int intermediate = 1; intermediate <= numberofvertices; intermediate++)
{
for (int source = 1; source <= numberofvertices; source++)
{
for (int destination = 1; destination <= numberofvertices; destination++)
{
if (distancematrix[source][intermediate] + distancematrix[intermediate][destination]
< distancematrix[source][destination])
distancematrix[source][destination] = distancematrix[source][intermediate]
+ distancematrix[intermediate][destination];
}
}
}
OUTPUT:
PROGRAM NO : 12
AIM: Write a java programs to implement backtracking algorithm for the N-queens problem.
THEORY:
The N Queen is the problem of placing N chess queens on an N×N chessboard so that no two
queens attack each other. For example, following is a solution for 4 Queen problem.
SOURCE CODE:
}
boolean solveNQ()
{
int board[][] = { { 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) {
System.out.print("Solution does not exist");
return false;
}
printSolution(board);
return true;
}
public static void main(String args[])
{
NQueenProblem Queen = new NQueenProblem();
Queen.solveNQ();
}
}
OUTPUT:
PROGRAM NO : 13
AIM: Write a java programs to implement backtracking algorithm for the Sum Of Subsets
problem
THEORY: Sum of Subsets: Given n distinct positive numbers, desired to find all
combinations of these numbers whose sums are m. this is called the sum of subsets
problem.Sum of Subset Problem is to find a subset of a given set S= {s1, s2… sn} of n
positive integers whose sum is equal to a given positive integer d. It is assumed that the set’s
elements are sorted in increasing order. The state-space tree can then be constructed as a
binary tree and applying backtracking algorithm, the solutions could be obtained. Some
instances of the problem may have no solutions.
SOURCE CODE:
import java.util.Scanner;
public class SumOfSubsets {
int[] w;
int[] x;
int sum;
public void process() {
getData();
}
private void getData() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of elements:");
int n = sc.nextInt();
w = new int[n + 1];
x = new int[n + 1];
int total = 0;
System.out.println("Enter " + n + " Elements :");
for (int i = 1; i < n + 1; i++) {
w[i] = sc.nextInt();
total += w[i];
}
System.out.println("Enter the sum to be obtained: ");
sum = sc.nextInt();
if (total < sum) {
System.out.println("Not possible to obtain the subset!!!");
System.exit(1);
}
subset(0, 1, total);
}
private void subset(int s, int k, int r) {
int i = 0;
x[k] = 1;
if (s + w[k] == sum) {
System.out.println();
for (i = 1; i <= k; i++) {
System.out.print("\t" + x[i]);
}
} else if ((s + w[k] + w[k + 1]) <= sum) {
subset(s + w[k], k + 1, r - w[k]);
}
if ((s + r - w[k]) >= sum && (s + w[k + 1]) <= sum) {
x[k] = 0;
subset(s, k + 1, r - w[k]);
}
}
public static void main(String[] args) {
new SumOfSubsets().process();
}
}
OUTPUT:
PROGRAM NO : 14
NAME OF THE EXPERIMENT: Hamiltonian Circuits problem.
Vignana Bharathi Institute of Technology Page 46
Design Analysis Of Algorithms
Dept. of Computer Science and Business Systems Master Lab Manual 2022 – 23
AIM: Write a java programs to implement backtracking algorithm for the Hamiltonian
Circuits problem.
THEORY:
Hamiltonian cycle problem are problems of determining whether a Hamiltonian path (a path
in an undirected or directed graph that visits each vertex exactly once) or a Hamiltonian cycle
exists in a given graph (whether directed or undirected). Both problems are NP-complete.
SOURCE CODE:
import java.util.Scanner;
import java.util.Arrays;
public class HamiltonianCycle
{
private int V, pathCount;
private int[] path;
private int[][] graph;
public void findHamiltonianCycle(int[][] g)
{
V = g.length;
path = new int[V];
Arrays.fill(path, -1);
graph = g;
try
{
path[0] = 0;
pathCount = 1;
solve(0);
System.out.println("No solution");
}
catch (Exception e)
{
System.out.println(e.getMessage());
display();
}
}
public void solve(int vertex) throws Exception
{
if (graph[vertex][0] == 1 && pathCount == V)
throw new Exception("Solution found");
if (pathCount == V)
return;
for (int v = 0; v < V; v++)
{
if (graph[vertex][v] == 1 )
{
path[pathCount++] = v;
graph[vertex][v] = 0;
graph[v][vertex] = 0;
if (!isPresent(v))
solve(v);
graph[vertex][v] = 1;
graph[v][vertex] = 1;
path[--pathCount] = -1;
}
}
}
public boolean isPresent(int v)
{
for (int i = 0; i < pathCount - 1; i++)
if (path[i] == v)
return true;
return false;
}
public void display()
{
System.out.print("\nPath : ");
for (int i = 0; i <= V; i++)
System.out.print(path[i % V] +" ");
System.out.println();
}
public static void main (String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("HamiltonianCycle Algorithm Test\n");
HamiltonianCycle hc = new HamiltonianCycle();
System.out.println("Enter number of vertices\n");
int V = scan.nextInt();
System.out.println("\nEnter matrix\n");
int[][] graph = new int[V][V];
for (int i = 0; i < V; i++)
for (int j = 0; j < V; j++)
graph[i][j] = scan.nextInt();
hc.findHamiltonianCycle(graph);
}
}
OUTPUT:
PROGRAM NO : 15
NAME OF THE EXPERIMENT: Graph Coloring Problem.
AIM: Write a java programs to implement backtracking algorithm for the Graph Coloring
Problem.
THEORY:
Graph Coloring problem involves assigning colors to certain elements of a graph subject ti
certain restrictions and constraints.In other words, the process of assigning colors to the
vertices such that no two adjacent vertices have the same color is called Graph coloring
problem.
SOURCE CODE:
import java.util.Scanner;
public class GraphColoring
{
private int V, numOfColors;
private int[] color;
private int[][] graph;
public void graphColor(int[][] g, int noc)
{
V = g.length;
numOfColors = noc;
color = new int[V];
graph = g;
try
{
solve(0);
System.out.println("No solution");
}
catch (Exception e)
{
System.out.println("\nSolution exists ");
display();
}
}
public void solve(int v) throws Exception
{
if (v == V)
throw new Exception("Solution found");
for (int c = 1; c <= numOfColors; c++)
{
if (isPossible(v, c))
{
color[v] = c;
solve(v + 1);
color[v] = 0;
}
}
}
OUTPUT: