You are on page 1of 52

Design Analysis Of Algorithms

Dept. of Computer Science and Business Systems Master Lab Manual 2022 – 23

Approved by AICTE, Affiliated to JNTU Hyderabad


Aushapur (V), Ghatkesar (M), R. R.Dist

DEPARTMENT OF
COMPUTER SCIENCE AND BUSINESS
SYSTEMS
ACADEMIC YEAR 2022-23

19BU3252– DESIGN ANALYSIS


OF ALGORITHMS- LAB
MANUAL
For III Year CSB

Prepared By :
xxxxxxx, Assistant Professor CSB

Vignana Bharathi Institute of Technology Page 1


Design Analysis Of Algorithms
Dept. of Computer Science and Business Systems Master Lab Manual 2022 – 23

INTRODUCTION TO DESIGN ANALYSIS OF ALGORITHMS


An algorithm is a set of steps of operations to solve a problem performing calculation,
data processing, and automated reasoning tasks. It is an efficient method that can be
expressed within finite amount of time and space. An algorithm is the best way to represent
the solution of a particular problem in a very simple and efficient way. If we have an
algorithm for a specific problem, then we can implement it in any programming language,
meaning that the algorithm is independent from any programming languages.
Algorithm Design: The important aspects of algorithm design include creating an
efficient algorithm to solve a problem in an efficient way using minimum time and space. To
solve a problem, different approaches can be followed. Some of them can be efficient with
respect to time consumption, whereas other approaches may be memory efficient. However,
one has to keep in mind that both time consumption and memory usage cannot be optimized
simultaneously.
Problem Development Steps:
The following steps are involved in solving computational problems.
 Problem definition
 Development of a model
 Specification of an Algorithm
 Designing an Algorithm
 Checking the correctness of an Algorithm
 Analysis of an Algorithm
 Implementation of an Algorithm
 Program testing
 Documentation
Characteristics of Algorithms: The main characteristics of algorithms are as follows:
 Algorithms must have a unique name
 Algorithms should have explicitly defined set of inputs and outputs
 Algorithms are well-ordered with unambiguous operations
 Algorithms halt in a finite amount of time. Algorithms should not run for infinity, i.e., an
algorithm must end at some point
Algorithm Analysis: Algorithm analysis is an important part of computational complexity
theory, which provides theoretical estimation for the required resources of an algorithm to
solve a specific computational problem. Analysis of algorithms is the determination of the
Vignana Bharathi Institute of Technology Page 2
Design Analysis Of Algorithms
Dept. of Computer Science and Business Systems Master Lab Manual 2022 – 23

amount of time and space resources required to execute it.


The Need for Analysis: Algorithms are often quite different from one another, though the
objectives of these algorithms are the same. Analysis of algorithm is the process of analyzing
the problem-solving capability of the algorithm in terms of the time and size required.
Generally, the following types of analysis are performed –
 Worst-case − the maximum number of steps taken on any instance of size a.
 Best-case − the minimum number of steps taken on any instance of size a.
 Average case − the average number of steps taken on any instance of size a.
Complexity of an algorithm is analyzed in two perspectives: Time and Space:
Time Complexity: It’s a function describing the amount of time required to run an algorithm
in terms of the size of the input.
Space Complexity: It’s a function describing the amount of memory an algorithm takes in
terms of the size of input to the algorithm.
Asymptotic Notations: Execution time of an algorithm depends on the instruction set,
processor speed, disk I/O speed, etc. Hence, we estimate the efficiency of an algorithm
asymptotically. Different types of asymptotic notations are used to represent the complexity
of an algorithm. Following asymptotic notations are used to calculate the running time
complexity of an algorithm.
 O − Big Oh
 Ω − Big omega
 θ − Big theta
 o − Little Oh
 ω − Little omega
Algorithm Design Techniques: The following is a list of several popular design approaches:
 Recursive
 Divide and Conquer
 Dynamic Programming
 Greedy Technique
 Brute Force
 Backtracking
 Branch and Bound

Vignana Bharathi Institute of Technology Page 3


Design Analysis Of Algorithms
Dept. of Computer Science and Business Systems Master Lab Manual 2022 – 23

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)

Domain Knowledge: Graduates of CSB-VBIT, will be able to synthesize mathematics,


 P1 science, engineering fundamentals, laboratory and work-based experiences to formulate
and solve engineering problems in Computer science domains.

Professional Employment: Graduates of CSB-VBIT, will succeed in entry-level


 P2 engineering positions with in Software & Hardware industries in regional, national, or
international industries and with government agencies.

Higher Degrees: Graduates of CSB-VBIT, will succeed in the pursuit of advanced


 P3 degrees in engineering or other fields where a solid foundation in mathematics, science,
and engineering Fundamentals is required.

Engineering Citizenship: Graduates of CSB-VBIT, will be prepared to communicate


P4 and work effectively on team-based engineering projects and will practice the ethics of
their profession consistent with a sense of social responsibility

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.

Vignana Bharathi Institute of Technology Page 5


Design Analysis Of Algorithms
Dept. of Computer Science and Business Systems Master Lab Manual 2022 – 23

PROGRAMMEOUTCOMES (PO)

An ability to apply knowledge of mathematics, science, and engineering to computer


a science problems.
 b An ability to design and develop programs, and to analyze and interpret gathered data
An ability to develop and/or design a system or system components to meet desired
c specifications, performance, and capabilities

d An ability to function on and/or develop leadership in multi-disciplinary teams.


 e An ability to identify and solve computer science problems.
f Understanding of professional and ethical responsibility.
g Ability to communicate effectively.
An ability to understand and correctly interpret the impact of engineering solutions in a
h social/global context.

An ability to engage in life-long learning to follow developments in computer science


 i engineering.
 j Knowledge of contemporary issues.
An ability to skillfully use modern engineering tools and techniques necessary for
k engineering design, analysis and applications.

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.

Vignana Bharathi Institute of Technology Page 6


Design Analysis Of Algorithms
Dept. of Computer Science and Business Systems Master Lab Manual 2022 – 23

 The components required pertaining to the experiment should be collected from


stores in-charge after duly filling in the requisition form.
 When the experiment is completed, should disconnect the setup made by them, and
should return all the components/instruments taken for the purpose.
 Any damage of the equipment or burn-out components will be viewed seriously
either by putting penalty or by dismissing the total group of students from the lab
for the semester/year.
 Students should be present in the labs for total scheduled duration.
 Students are required to prepare thoroughly to perform the experiment before
coming to laboratory.

HARDWARE & SOFTWARE 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 Compiler

Vignana Bharathi Institute of Technology Page 7


Design Analysis Of Algorithms
Dept. of Computer Science and Business Systems Master Lab Manual 2022 – 23

SYLLABUS AS PER JNTUH

DESIGN ANALYSIS OF ALGORITHMS LAB SYLLABUS

III Year B.Tech. CSB - II Sem

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

Vignana Bharathi Institute of Technology Page 8


Design Analysis Of Algorithms
Dept. of Computer Science and Business Systems Master Lab Manual 2022 – 23

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 the Depth First Search (DFS)


3 algorithm for a graph. 15

Write a. java program to implement the Breadth First Search (BFS)


4 algorithm for a graph. 18

Write a java program to implement greedy algorithm for job sequencing


5 with deadlines. 20

Write a java program to implement Dijkstra’s algorithm for the Single


6 source shortest path problem. 24

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


7 minimum cost spanning tree. 26

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


8 minimum cost spanning tree. 30

Write a java program to implement Dynamic Programming algorithm for


9 the 0/1 Knapsack problem. 35

Write a java program to implement Dynamic Programming algorithm for


10 the Optimal Binary Search Tree Problem. 38

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

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


12 queens problem. 43

Write a java program to implement the backtracking algorithm for the


13 sum of subsets problem. 45

Write a java program to implement the backtracking algorithm for the


14 Hamiltonian Circuits problem. 47

15 Write a java program to Implement Graph Coloring using Back Tracking. 50

INDEX
PROGRAM NO : 1.

Vignana Bharathi Institute of Technology Page 9


Design Analysis Of Algorithms
Dept. of Computer Science and Business Systems Master Lab Manual 2022 – 23

NAME OF THE EXPERIMENT :. Merge Sort

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];

Vignana Bharathi Institute of Technology Page 10


Design Analysis Of Algorithms
Dept. of Computer Science and Business Systems Master Lab Manual 2022 – 23

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:

Vignana Bharathi Institute of Technology Page 11


Design Analysis Of Algorithms
Dept. of Computer Science and Business Systems Master Lab Manual 2022 – 23

PROGRAM NO : 2

NAME OF THE EXPERIMENT: Quick Sort

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

Vignana Bharathi Institute of Technology Page 12


Design Analysis Of Algorithms
Dept. of Computer Science and Business Systems Master Lab Manual 2022 – 23

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) {

Vignana Bharathi Institute of Technology Page 13


Design Analysis Of Algorithms
Dept. of Computer Science and Business Systems Master Lab Manual 2022 – 23

int temp = input[i];


input[i] = input[j];
input[j] = temp;
}
}

OUTPUT:

PROGRAM NO : 3.

NAME OF THE EXPERIMENT: Depth First Search

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

Vignana Bharathi Institute of Technology Page 14


Design Analysis Of Algorithms
Dept. of Computer Science and Business Systems Master Lab Manual 2022 – 23

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;

Vignana Bharathi Institute of Technology Page 15


Design Analysis Of Algorithms
Dept. of Computer Science and Business Systems Master Lab Manual 2022 – 23

Scanner scanner = null;


try
{
System.out.println("Enter the number of nodes in the graph");
scanner = new Scanner(System.in);
number_of_nodes = scanner.nextInt();
int adjacency_matrix[][] = new int[number_of_nodes + 1][number_of_nodes + 1];
System.out.println("Enter the adjacency matrix");
for (int i = 1; i <= number_of_nodes; i++)
for (int j = 1; j <= number_of_nodes; j++)
adjacency_matrix[i][j] = scanner.nextInt();
System.out.println("Enter the source for the graph");
source = scanner.nextInt();
System.out.println("The DFS Traversal for the graph is given by ");
DFS dfs = new DFS();
dfs.dfs(adjacency_matrix, source);
}catch(InputMismatchException inputMismatch)
{
System.out.println("Wrong Input format");
}
scanner.close();
}
}

OUTPUT:

Vignana Bharathi Institute of Technology Page 16


Design Analysis Of Algorithms
Dept. of Computer Science and Business Systems Master Lab Manual 2022 – 23

PROGRAM NO : 4

NAME OF THE EXPERIMENT: Breadth First Search.

Vignana Bharathi Institute of Technology Page 17


Design Analysis Of Algorithms
Dept. of Computer Science and Business Systems Master Lab Manual 2022 – 23

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;

Vignana Bharathi Institute of Technology Page 18


Design Analysis Of Algorithms
Dept. of Computer Science and Business Systems Master Lab Manual 2022 – 23

}
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

NAME OF THE EXPERIMENT: job sequencing with deadlines.

Vignana Bharathi Institute of Technology Page 19


Design Analysis Of Algorithms
Dept. of Computer Science and Business Systems Master Lab Manual 2022 – 23

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++)
{

Vignana Bharathi Institute of Technology Page 20


Design Analysis Of Algorithms
Dept. of Computer Science and Business Systems Master Lab Manual 2022 – 23

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];

Vignana Bharathi Institute of Technology Page 21


Design Analysis Of Algorithms
Dept. of Computer Science and Business Systems Master Lab Manual 2022 – 23

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:

Vignana Bharathi Institute of Technology Page 22


Design Analysis Of Algorithms
Dept. of Computer Science and Business Systems Master Lab Manual 2022 – 23

PROGRAM NO : 6

Vignana Bharathi Institute of Technology Page 23


Design Analysis Of Algorithms
Dept. of Computer Science and Business Systems Master Lab Manual 2022 – 23

NAME OF THE EXPERIMENT: Single Source Shortest Path Problem.

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

Vignana Bharathi Institute of Technology Page 24


Design Analysis Of Algorithms
Dept. of Computer Science and Business Systems Master Lab Manual 2022 – 23

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

Vignana Bharathi Institute of Technology Page 25


Design Analysis Of Algorithms
Dept. of Computer Science and Business Systems Master Lab Manual 2022 – 23

NAME OF THE EXPERIMENT: minimum cost spanning tree.

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[][])

Vignana Bharathi Institute of Technology Page 26


Design Analysis Of Algorithms
Dept. of Computer Science and Business Systems Master Lab Manual 2022 – 23

{
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)
{

Vignana Bharathi Institute of Technology Page 27


Design Analysis Of Algorithms
Dept. of Computer Science and Business Systems Master Lab Manual 2022 – 23

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);

Vignana Bharathi Institute of Technology Page 28


Design Analysis Of Algorithms
Dept. of Computer Science and Business Systems Master Lab Manual 2022 – 23

prims.printMST();
} catch (InputMismatchException inputMismatch)
{
System.out.println("Wrong Input Format");
}
scan.close();
}
}

OUTPUT:

PROGRAM NO : 8

Vignana Bharathi Institute of Technology Page 29


Design Analysis Of Algorithms
Dept. of Computer Science and Business Systems Master Lab Manual 2022 – 23

NAME OF THE EXPERIMENT: minimum cost spanning tree.

AIM: Write A Java Program to implement Kruskal’s algorithm to generate minimum cost
spanning tree.

THEORY:

Kruskal's algorithm is a minimum-spanning-tree algorithm which finds an edge of the


least possible weight that connects any two trees in the forest.[1] It is a greedy algorithm in
graph theory as it finds a minimum spanning tree for a connected weighted graph adding
increasing cost arcs at each step.[1] This means it finds a subset of the edges that forms a tree
that includes every vertex, where the total weight of all the edges in the tree is minimized. If
the graph is not connected, then it finds a minimum spanning forest (a minimum spanning
tree for each connected component)

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;

Vignana Bharathi Institute of Technology Page 30


Design Analysis Of Algorithms
Dept. of Computer Science and Business Systems Master Lab Manual 2022 – 23

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();
}

Vignana Bharathi Institute of Technology Page 31


Design Analysis Of Algorithms
Dept. of Computer Science and Business Systems Master Lab Manual 2022 – 23

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

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] = MAX_VALUE;
}
}
}
KruskalAlgorithm kruskalAlgorithm = new KruskalAlgorithm(number_of_vertices);
kruskalAlgorithm.kruskalAlgorithm(adjacency_matrix);
scan.close();
}
}
class Edge
{
int sourcevertex;
int destinationvertex;
int weight;
}
class EdgeComparator implements Comparator<Edge>
{

public int compare(Edge edge1, Edge edge2)


{
if (edge1.weight < edge2.weight)
return -1;
if (edge1.weight > edge2.weight)
return 1;
return 0;
}
}

Vignana Bharathi Institute of Technology Page 32


Design Analysis Of Algorithms
Dept. of Computer Science and Business Systems Master Lab Manual 2022 – 23

class CheckCycle
{
private Stack<Integer> stack;
private int adjacencyMatrix[][];
public CheckCycle()
{

stack = new Stack<Integer>();


}
public boolean checkCycle(int adjacency_matrix[][], int source)
{
boolean cyclepresent = false;
int number_of_nodes = adjacency_matrix[source].length - 1;
adjacencyMatrix = new int[number_of_nodes + 1][number_of_nodes + 1];
for (int sourcevertex = 1; sourcevertex <= number_of_nodes; sourcevertex++)
{
for (int destinationvertex = 1; destinationvertex <= number_of_nodes; destinationvertex++)
{
adjacencyMatrix[sourcevertex][destinationvertex] =
adjacency_matrix[sourcevertex][destinationvertex];
}
}
int visited[] = new int[number_of_nodes + 1];
int element = source;
int i = source;
visited[source] = 1;
stack.push(source);
while (!stack.isEmpty())
{
element = stack.peek();
i = element;
while (i <= number_of_nodes)
{
if (adjacencyMatrix[element][i] >= 1 && visited[i] == 1)
{
if (stack.contains(i))
{
cyclepresent = true;
return cyclepresent;
}
}
if (adjacencyMatrix[element][i] >= 1 && visited[i] == 0)
{
stack.push(i);
visited[i] = 1;
adjacencyMatrix[element][i] = 0;// mark as labelled;
adjacencyMatrix[i][element] = 0;
element = i;
i = 1;
continue;

Vignana Bharathi Institute of Technology Page 33


Design Analysis Of Algorithms
Dept. of Computer Science and Business Systems Master Lab Manual 2022 – 23

}
i++;
}

stack.pop();
}
return cyclepresent;
}

OUTPUT:

PROGRAM NO : 9

Vignana Bharathi Institute of Technology Page 34


Design Analysis Of Algorithms
Dept. of Computer Science and Business Systems Master Lab Manual 2022 – 23

NAME OF THE EXPERIMENT: 0/1 Knapsack problem.

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;

Vignana Bharathi Institute of Technology Page 35


Design Analysis Of Algorithms
Dept. of Computer Science and Business Systems Master Lab Manual 2022 – 23

}
}
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:

Vignana Bharathi Institute of Technology Page 36


Design Analysis Of Algorithms
Dept. of Computer Science and Business Systems Master Lab Manual 2022 – 23

PROGRAM NO : 10

Vignana Bharathi Institute of Technology Page 37


Design Analysis Of Algorithms
Dept. of Computer Science and Business Systems Master Lab Manual 2022 – 23

NAME OF THE EXPERIMENT: Optimal Binary Search Tree problem.

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[],

Vignana Bharathi Institute of Technology Page 38


Design Analysis Of Algorithms
Dept. of Computer Science and Business Systems Master Lab Manual 2022 – 23

int n)
{
return optCost_memoized(freq, 0, n - 1);
}

public static void main(String[] args)


{
int keys[] = { 10, 12, 20 };
int freq[] = { 34, 8, 50 };
int n = keys.length;
for (int i = 0; i < n; i++)
Arrays.fill(cost[i], 0);
for (int i = 0; i < n; i++)
cost[i][i] = freq[i];
System.out.println(
"Cost of Optimal BST is "
+ optimalSearchTree(keys, freq, n));

}
}

OUTPUT:

PROGRAM NO : 11

Vignana Bharathi Institute of Technology Page 39


Design Analysis Of Algorithms
Dept. of Computer Science and Business Systems Master Lab Manual 2022 – 23

NAME OF THE EXPERIMENT: all pairs shortest path problem.

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

Vignana Bharathi Institute of Technology Page 40


Design Analysis Of Algorithms
Dept. of Computer Science and Business Systems Master Lab Manual 2022 – 23

for (int source = 1; source <= numberofvertices; source++)


System.out.print("\t" + source);
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(distancematrix[source][destination] + "\t");
}
System.out.println();
}
}
public static void main(String... arg)
{
int adjacency_matrix[][];
int numberofvertices;
Scanner scan = new Scanner(System.in);
System.out.println("Enter the number of vertices");
numberofvertices = scan.nextInt();
adjacency_matrix = new int[numberofvertices + 1][numberofvertices + 1];
System.out.println("Enter the Weighted Matrix for the graph");
for (int source = 1; source <= numberofvertices; source++)
{
for (int destination = 1; destination <= numberofvertices; destination++)
{
adjacency_matrix[source][destination] = scan.nextInt();
if (source == destination)
{
adjacency_matrix[source][destination] = 0;
continue;
}
if (adjacency_matrix[source][destination] == 0)
{
adjacency_matrix[source][destination] = INFINITY;
}
}
}
System.out.println("The Transitive Closure of the Graph");
FloydWarshall floydwarshall = new FloydWarshall(numberofvertices);
floydwarshall.floydwarshall(adjacency_matrix);
scan.close();
}
}

Vignana Bharathi Institute of Technology Page 41


Design Analysis Of Algorithms
Dept. of Computer Science and Business Systems Master Lab Manual 2022 – 23

OUTPUT:

PROGRAM NO : 12

Vignana Bharathi Institute of Technology Page 42


Design Analysis Of Algorithms
Dept. of Computer Science and Business Systems Master Lab Manual 2022 – 23

NAME OF THE EXPERIMENT: N-queens problem.

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:

public class NQueenProblem {


final int N = 8;
void printSolution(int board[][])
{
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++)
System.out.print(" " + board[i][j]+ " ");
System.out.println();
}
}
boolean isSafe(int board[][], int row, int col)
{
int i, j;
for (i = 0; i < col; i++)
if (board[row][i] == 1)
return false;
for (i = row, j = col; i >= 0 && j >= 0; i--, j--)
if (board[i][j] == 1)
return false;
for (i = row, j = col; j >= 0 && i < N; i++, j--)
if (board[i][j] == 1)
return false;
return true;
}
boolean solveNQUtil(int board[][], int col)
{
if (col >= N)
return true;
for (int i = 0; i < N; i++) {
if (isSafe(board, i, col)) {
board[i][col] = 1;
if (solveNQUtil(board, col + 1) == true)
return true;
board[i][col] = 0; // BACKTRACK
}
}
return false;

Vignana Bharathi Institute of Technology Page 43


Design Analysis Of Algorithms
Dept. of Computer Science and Business Systems Master Lab Manual 2022 – 23

}
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

Vignana Bharathi Institute of Technology Page 44


Design Analysis Of Algorithms
Dept. of Computer Science and Business Systems Master Lab Manual 2022 – 23

NAME OF THE EXPERIMENT: Sum Of Subsets problem.

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;

Vignana Bharathi Institute of Technology Page 45


Design Analysis Of Algorithms
Dept. of Computer Science and Business Systems Master Lab Manual 2022 – 23

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;

Vignana Bharathi Institute of Technology Page 47


Design Analysis Of Algorithms
Dept. of Computer Science and Business Systems Master Lab Manual 2022 – 23

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:

Vignana Bharathi Institute of Technology Page 48


Design Analysis Of Algorithms
Dept. of Computer Science and Business Systems Master Lab Manual 2022 – 23

PROGRAM NO : 15
NAME OF THE EXPERIMENT: Graph Coloring Problem.

Vignana Bharathi Institute of Technology Page 49


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

Vignana Bharathi Institute of Technology Page 50


Design Analysis Of Algorithms
Dept. of Computer Science and Business Systems Master Lab Manual 2022 – 23

public boolean isPossible(int v, int c)


{
for (int i = 0; i < V; i++)
if (graph[v][i] == 1 && c == color[i])
return false;
return true;
}
public void display()
{
System.out.print("\nColors : ");
for (int i = 0; i < V; i++)
System.out.print(color[i] +" ");
System.out.println();
}
public static void main (String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Graph Coloring Algorithm Test\n");
GraphColoring gc = new GraphColoring();
System.out.println("Enter number of verticesz\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();
System.out.println("\nEnter number of colors");
int c = scan.nextInt();
gc.graphColor(graph, c);
}
}

OUTPUT:

Vignana Bharathi Institute of Technology Page 51


Design Analysis Of Algorithms
Dept. of Computer Science and Business Systems Master Lab Manual 2022 – 23

Vignana Bharathi Institute of Technology Page 52

You might also like