Sunteți pe pagina 1din 66

16CS311 - ALGORITHMS LABORATORY

M.KUMARASAMY COLLEGE OF ENGINEERING


(Autonomous)
AFFILIATED TO ANNA UNIVERSITY CHENNAI

PERTINENT TO REGULATION 2016

16CS311
ALGORITHMS LABORATORY

M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 1
16CS311 - ALGORITHMS LABORATORY

Exercise Number: 1

Title of the Exercise: Randomized Merge Sort


---------------------------------------------------------------------------------------------------------------
OBJECTIVE OF THE EXPERIMENT
To sort ‘n’ randomly generated elements using Merge Sort algorithm
ALGORITHM
Step 1: Call a function to generate list of random numbers (integers)
Step 2: Record clock time
Step 3: Call a Merge sort function to sort n randomly generated elements.
Step 4: Merge sort function calls itself recursively for the two half portions
Step 5: Record clock time.
Step 6: Measure difference in clock time to get elapse time to sort n elements using
Merge sort.
Step 7: Print the Sorted ‘ n’ elements and time taken to sort.
Step 8: Repeat the above steps for different n values.

PROGRAM
import java.util.Random;
import java.util.Scanner;
public class Randommergesort {
public static void main(String[] args) {
int a[]= new int[100000];
Scanner in = new Scanner(System.in);
long start, end;
System.out.println("********** MERGE SORT PROGRAM *********");
System.out.println("Enter the number of elements to be sorted");
int n = in.nextInt();
Random rand= new Random();
for(int i=0;i<n;i++)
a[i]=rand.nextInt(100);
System.out.println("Array elements to be sorted are");
for(int i=0; i<n; i++)
System.out.print(a[i]+" ");
start=System.nanoTime();
mergesort(a,0,n-1);
end=System.nanoTime();
System.out.println("\nThe sorted elements are");
for(int i=0; i<n; i++)
System.out.print(a[i]+" ");

M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 2
16CS311 - ALGORITHMS LABORATORY

}
static void mergesort(int a[], int low, int high){
int mid;
if(low < high){
mid = (low+high)/2;
mergesort(a, low, mid);
mergesort(a, mid+1, high);
merge(a, low, mid, high);
}
}
static void merge(int a[], int low, int mid, int high){
int i, j, h, k, b[]= new int[100000];
h=low; i=low; j=mid+1;
while((h<=mid) && (j<=high)){
if(a[h] < a[j]){
b[i] = a[h]; h=h+1;
}
else
{
b[i] = a[j]; j=j+1;
}
i = i+1;
}
if(h > mid){
for(k=j; k<=high; k++){
b[i] = a[k]; i = i+1;
}
}
else
{
for(k=h; k<=mid; k++){
b[i] = a[k]; i = i+1;
}
}
for(k=low; k<= high; k++)
a[k] = b[k];
}
}

OUTPUT
********** MERGE SORT PROGRAM *********
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 3
16CS311 - ALGORITHMS LABORATORY

Enter the number of elements to be sorted


10
Array elements to be sorted are
34 83 89 21 62 36 48 90 36 85
The sorted elements are
21 34 36 36 48 62 83 85 89 90
The time taken to sort is 6051702ns
******** *********************** *******
RESULT:
Thus the elements are sorted using Randomized Merge Sort
VIVA VOCE
1. What is the average case complexity for merge sort algorithm
a.O(n) b.O(n*n) c.O(nlogn) d.O(logn)
Ans:c

2. What is the worst case complexity for merge sort algorithm


a.O(n) b.O(n*n) c.O(nlogn) d.O(logn)
Ans:c

3. What is the best case complexity for merge sort algorithm


a.O(n) b.O(n*n) c.O(nlogn) d.O(logn)
Ans:c

4. What is the output of merge sort after the 1st pass given the following sequence of
numbers: 25 57 48 37 12 92 86 33
a. 48 25 37 12 57 86 33 92
b. 12 25 33 37 48 57 86 92
c.12 25 33 37 48 57 86 92
d. 25 57 37 48 12 92 33 86
Ans:d

5. What is the output of merge sort after the 2nd pass given the following sequence of
numbers: 25 57 48 37 12 92 86 33
a. 48 25 37 12 57 86 33 92
b. 12 25 33 37 48 57 86 92
c.25 37 48 57 12 33 86 92
d. 25 57 37 48 12 92 33 86
Ans:c

6. What is the output of merge sort after the 3rd pass given the following sequence of
numbers: 25 57 48 37 12 92 86 33
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 4
16CS311 - ALGORITHMS LABORATORY

a. 12 25 33 37 48 57 86 92
b. 12 25 33 37 48 57 86 92
c.12 25 33 37 48 57 86 92
d. 25 57 37 48 12 92 33 86
Ans:a

7. In which cases are the time complexities same in merge sort?


a. Worst and Best
b. Best and Average
c. Worst and Average
d. Worst, average and Best
Ans:d

8.Total numbers of passes in merge sort of ‘n’ numbers is _______.


a.n
b.n-1
c.log(n)
d.nlogn
Ans:c

9.Merge sort is based on the divide and conquer strategy.it consists of the following
steps
a. Divide,Recursive and Conquer
b. Divide and Conquer
c. Divide and Recursive
d. None of the above
Ans. a

10.Given two sorted lists of size m,n ,the number of comparisons needed in the worst
case by the merge sort algorithm is
a.mn b.max(m,n) c.min(m,n) d.m+n-1
Ans:d
Each comparison puts 1 element in the final sorted array. So,in the worst case m+n-1
comparisons are needed.

11. Suppose the array A contains 14 elements as follows:


A = [66, 33, 40, 22, 55, 88, 60, 11, 80, 20, 50, 44, 77, 30]
How many Passes are required to sort the above array A using the Merge sort
algorithm?
a. 3
b. 4
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 5
16CS311 - ALGORITHMS LABORATORY

c. 5
d. 7
e. 14
Ans. c

12. If you are provided with two files whose contents are sorted and the requirement is
to copy the contents of both the files into a third file which should be sorted. In this case
which of the sorting techniques can be an appropriate one?
a.Selection sort
b.Bubble sort
c.Merge sort
d.insertion sort
Ans:c

13. The merge sort algorithm involves the following steps.


(i) Recursively sort the 1st and 2nd halves separately
(ii) Merge the two-sorted halves into a sorted group.
(iii) If the number of items to sort is 0 or 1, return.

Which is the correct order of instructions in merge sort algorithm?


(a) (i),(ii),(iii)
(b) (ii),(iii),(i)
(c) (iii),(ii),(i)
(d) (iii),(i),(ii)
Ans:d

14. What is the output of merge sort after the 1st pass given the following sequence of
numbers : 3,41,52,26,38,57,9,49
a. 3,41,26,52,38,57,9,49
b. 3,41,52,26,38,57,9,49
c. 3,41,52,26,38,57,9,49
d. 3,41,38,26,52,9,49,57
Ans. a

15. What is the output of merge sort after the 2nd pass given the following sequence of
numbers : 3,41,52,26,38,57,9,49
a. 3,26,41,52,38,9,49,57
b. 3,26,41,52,9,38,49,57
c. 3,26,38,9,49,57,41,52
d. 3,26,41,52,38,49,57,9
Ans. b
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 6
16CS311 - ALGORITHMS LABORATORY

Exercise Number: 2(a)

Title of the Exercise: Implementation of BFS


---------------------------------------------------------------------------------------------------------------
OBJECTIVE OF THE EXPERIMENT
To write a java program to perform a Breadth First Search in the given graph.
List.
DESCRIPTION

There are many ways to traverse graphs. BFS is the most commonly used approach.

BFS is a traversing algorithm where you should start traversing from a selected node
(source or starting node) and traverse the graph layerwise thus exploring the neighbour
nodes (nodes which are directly connected to source node). You must then move
towards the next-level neighbour nodes.
As the name BFS suggests, you are required to traverse the graph breadthwise as
follows:
First move horizontally and visit all the nodes of the current layer
Move to the next layer
ALGORITHM
1. Declare all necessary variables and initialize those variables.
2. Get the number of vertices.
3. Store the number of vertices in the variable n.
4. Create a adjacency matrix. Using for loop define edges between the nodes are
present or not.
5. Initialize the queue is empty and m[0]=1 denotes the source node is found.
6. From the source node. traverse through the nodes which have edges from the source
node and move these nodes to found not handle queue.
7. Repeat this process untill all nodes are visited.
8. Finally print order of accessed nodes
PROGRAM
import java.io.*;
class bfs
{
public static void main(String args[])throws IOException
{
int i,n,j,k;

M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 7
16CS311 - ALGORITHMS LABORATORY

System.out.println("No of vertices:");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
n=Integer.parseInt(br.readLine());
int q[]=new int[10];
int m[]=new int[10];
int a[][]=new int[10][10];
for(i=0;i<n;i++)
{
m[i]=0;
}
System.out.println("\n Enter 1 if edge is present,0 if not");
for(i=0;i<n;i++)
{
System.out.println("\n");
for(j=i;j<n;j++)
{
System.out.println("Edge between"+(i+1)+"and"+(j+1)+":");
a[i][j]=Integer.parseInt(br.readLine());
a[j][i]=a[i][j];
}
a[i][i]=0;
}
System.out.println("\n Order of accessed nodes:\n");
q[0]=0;
m[0]=1;
int u;
int node=1;MBCET ME/CSE ADVANCED DATA STRUCTURES LAB –CP7111
int beg1=1;
int beg=0;
while(node>0)
{
u=q[beg];
beg++;
System.out.println(""+(u+1));
node--;
for(j=0;j<n;j++)
{
if(a[u][j]==1)
{
if(m[j]==0)
{
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 8
16CS311 - ALGORITHMS LABORATORY

m[j]=1;
q[beg1]=j;
node++;
beg1++;
}
}
}
}
}
OUTPUT
Number of vertices: 6
Enter 1 if edge is present, 0 if not
Edges between 1 and 1: 0
1 and 2: 1
1 and 3: 1
1 and 4: 1
1 and 5: 0
1 and 6: 0
Edges between 2 and 2: 0
2 and 3: 1
2 and 4: 0
2 and 5: 1
2 and 6: 0
Edges between 3 and 3: 0
3 and 4: 1
3 and 5: 1
3 and 6: 1
Edges between 4 and 4: 0
4 and 5: 0
4 and 6: 1
Edges between 5 and 3: 0
5 and 4: 0
Edges between 6 and 6: 0
Order of accessed nodes: 1
2
3
4
5
6

RESULT
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 9
16CS311 - ALGORITHMS LABORATORY

Thus the java program for performing breadth first search algorithm has been executed
successfully and the output is verified

VIVA VOCE
1. Define a graph.
A graph is a non-linear data structure that represents less relationship between its
adjacent elements. There is no hierarchical relationship between the adjacent elements
in case of graphs.

2. List the two types of graphs.


• Directed graph
• Undirected graph

3. Define undirected graph.


If an edge between any two nodes in a graph is not directionally oriented a graph is
called as undirected graph. It is also referred as unqualified graph.

4. Define directed graph.


If an edge between any two nodes in a graph is directionally oriented, a graph is called
as directed graph; it is also referred as a digraph.
What is Acyclic graph?
If there is no path from any node back to itself then the graph is said to be acyclic graph.
5. Define a path in a graph.
A path in a graph is defined as a sequence of distinct vertices each adjacent to the next,
except possibly the first vertex and last vertex is different.

6. Define a cycle in a graph.


A cycle is a path containing at least three vertices such that the starting and the ending
vertices are the same.

7. Define a strongly connected graph.


A directed graph is said to be strongly connected if, for every pair of distinct vertices
there is a directed path from every vertex to every other vertex. It is also referred as a
complete graph.

8. What do you mean by Complete Graph?


In a graph if there exists the path from any vertex to any other vertex, then the graph is
called as Complete Graph.

9.What is Acyclic graph?


If there is no path from any node back to itself then the graph is said to be acyclic graph.
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 10
16CS311 - ALGORITHMS LABORATORY

Exercise Number: 2(b)

Title of the Exercise: Implementation of DFS


---------------------------------------------------------------------------------------------------------------
OBJECTIVE OF THE EXPERIMENT
To write a java program to perform a Depth First Search in the given graph.
DESCRIPTION
The DFS algorithm is a recursive algorithm that uses the idea of backtracking. It involves
exhaustive searches of all the nodes by going ahead, if possible, else by backtracking.

Here, the word backtrack means that when you are moving forward and there are no
more nodes along the current path, you move backwards on the same path to find nodes
to traverse. All the nodes will be visited on the current path till all the unvisited nodes
have been traversed after which the next path will be selected.

This recursive nature of DFS can be implemented using stacks. The basic idea is as
follows:
Pick a starting node and push all its adjacent nodes into a stack.
Pop a node from stack to select the next node to visit and push all its adjacent nodes into
a stack.
Repeat this process until the stack is empty. However, ensure that the nodes that are
visited are marked. This will prevent you from visiting the same node more than once. If
you do not mark the nodes that are visited and you visit the same node more than once,
you may end up in an infinite loop.
ALGORITHM
1. Get the number of vertices.
2. To construct edges of graph get 1if edge is present else 0 and repeat the same for all
the vertices of the graph.
3. Store edges in adjacency matrix a[][] and traverse from source node.
4. Initially store m[] with zero .since nodes in graph are not visited. if visited make m[]
as one.
5. To access the order of nodes, for each node check the node is visited or not using m[].
6. In dfs() method ,node visited is marked as one,m[]=1.next node j is traversed by
checking the condition that edge between i and j is present using adjacency matrix a[]
[]=1 and next node to be traversed is not visited, m[]=0.
7. The above step is repeated for all the nodes in the graph.
8. The order of accessed node is outputted.

M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 11
16CS311 - ALGORITHMS LABORATORY

PROGRAM
import java.io.*;
class dfs
{
static void dfs(int a[][], int m[], int i, int n)
{
int j;
System.out.println("\t" + (i+1));
m[i] = 1;
for(j=0; j<n; j++)
if(a[i][j]==1 && m[j]==0)
dfs(a,m,j,n);
}

public static void main(String args[]) throws IOException


{
int n, i, j;
System.out.println("No. of vertices : ");
BufferedReader br= new BufferedReader (new InputStreamReader(System.in));
n =Integer.parseInt(br.readLine());
int m[]= new int[n];
int a[][] = new int[n][n];
for (i=0; i<n; i++)
{
m[i] = 0;
}
System.out.println("\n\nEnter 1 if edge is present, 0 if not");
for (i=0; i<n; i++)
{
System.out.println("\n");
for (j=i; j<n; j++)
{
System.out.println("Edge between " + (i+1) + " and " + (j+1)+ " : ");
a[i][j] =Integer.parseInt(br.readLine());
a[j][i]=a[i][j];
}
a[i][i] = 0;
}
System.out.println("\nOrder of accessed nodes : \n");
for (i=0; i<n; i++)
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 12
16CS311 - ALGORITHMS LABORATORY

if (m[i]==0)
dfs(a,m,i,n);
}
}

OUTPUT
Number of vertices: 6
Enter 1 if edge is present, 0 if not
Edges between 1 and 1: 0
1 and 2: 1
1 and 3: 1
1 and 4: 1
1 and 5: 0
1 and 6: 0
Edges between 2 and 2: 0
2 and 3: 1
2 and 4: 0
2 and 5: 1
2 and 6: 0
Edges between 3 and 3: 0
3 and 4: 1
3 and 5: 1
3 and 6: 1
Edges between 4 and 4: 0
4 and 5: 0
4 and 6: 1
Edges between 5 and 3: 0
5 and 4: 0
Edges between 6 and 6: 0
Order of accessed nodes: 1
2
3
4
6
5

RESULT
Thus the java program for performing depth first search algorithm has been executed
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 13
16CS311 - ALGORITHMS LABORATORY

successfully and the output is verified


VIVA VOCE
1. What is meant by traversing a graph? State the different ways of traversing a graph.
Traversing a graph means visiting all the nodes in the graph. In many practical
applications traversing a graph is important, such that each vertex is visited once
systematically by traversing through minimum number of paths. The two important
graph traversal methods are,
• Depth-first traversal(or) Depth-first search(DFS)
• Breath-first traversal(or)Breath-first search(BFS)

2. Define a weakly connected graph.


A directed graph is said to be weakly connected graph, if any vertex doesn’t have a
directed path to any other vertices.

3. Define a weighted graph.


A graph is said to be weighted graph if every edge in the graph is assigned some weight
or value. The weight of an edge is a positive value that may be representing the distance
between the vertices or the weights of the edges along the path.

4. Define incidence matrix.


Incidence matrix is a representation used to represent a graph with zeros and ones. A
graph containing n vertices can be represented by a matrix with m rows and n columns.
The matrix is formed by storing 1 in its ith row and jth column corresponding to the
matrix, if there exists a ith vertex, connected to one end of the jth edge and a 0, if there
is no ith vertex, connected to any end of the jth edge of the graph.

5. Define adjacency matrix.


Adjacency matrix is a representation used to represent a graph with zeros and ones. A
graph containing n vertices can be represented by a matrix with n rows n columns. The
matrix is formed by storing 1 in its ith row and jth coilumn of the matrix, if there exists
an edge between ith and jth vertex of the graph, and a 0, if there is no edge between ith
and jth vertex of the graph.

6. Define adjacency list.


A graph containing m vertices and n edges can be represented using a linked list,
referred to as adjacency list.

7. Define path matrix.


A graph containing n vertices can be represented by a matrix with n rows and n
columns. The matrix is formed by storing 1 in its ith row and jth column of the matrix, if
there exists an edge between ith and jth vertex of the graph, and a 0, if there is no edge
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 14
16CS311 - ALGORITHMS LABORATORY

between ith and jth vertex of the graph, such a matrix is referred to as path matrix.
8.Define DFS.
DFS means Depth First search it is like a preorder traversal of a tree. It is continuous
searching for the unvisited nodes in the forward direction based on the recursive
process.

9.What is called Biconnectivity?


A connected undirected graph is biconnected if there are no vertices whose removal
disconnects the rest of the graph.

M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 15
16CS311 - ALGORITHMS LABORATORY

Exercise Number: 3(a)

Title of the Exercise: Prim’s Algorithm


---------------------------------------------------------------------------------------------------------------

OBJECTIVE OF THE EXPERIMENT


To create a simple java program to implement Minimum Spanning Tree using
Prims Algorithm.
DESCRIPTION
Choose a node and build a tree from there selecting at every stage the shortest available
edge that
can extend the tree to an additional node.
• Prim's algorithm has the property that the edges in the set A always form a single tree.
• We begin with some vertex v in a given graph G =(V, E), defining the initial set of
vertices A.
• In each iteration, we choose a minimum-weight edge (u, v), connecting a vertex v in
the set
A to the vertex u outside of set A.
• The vertex u is brought in to A. This process is repeated until a spanning tree is
formed.
• Like Kruskal's algorithm, here too, the important fact about MSTs is we always choose
the
smallest-weight edge joining a vertex inside set A to the one outside the set A.
• The implication of this fact is that it adds only edges that are safe for A; therefore when
the
algorithm terminates, the edges in set A form a MST

ALGORITHM
1) Create a set mstSet that keeps track of vertices already included in MST.
2) Assign a key value to all vertices in the input graph. Initialize all key values as
INFINITE. Assign key value as 0 for the first vertex so that it is picked first.
3) While mstSet doesn’t include all vertices
a) Pick a vertex u which is not there in mstSet and has minimum key value.
b) Include u to mstSet.
c) Update key value of all adjacent vertices of u. To update the key values, iterate
through all adjacent vertices. For every adjacent vertex v, if weight of edge u-v is
less than the previous key value of v, update the key value as weight of u-v

M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 16
16CS311 - ALGORITHMS LABORATORY

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


{
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 17
16CS311 - ALGORITHMS LABORATORY

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;
}
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 18
16CS311 - ALGORITHMS LABORATORY

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();
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 19
16CS311 - ALGORITHMS LABORATORY

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

Enter the number of vertices

Enter the Weighted Matrix for the graph

04005

40361

03062

06607

51270

M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 20
16CS311 - ALGORITHMS LABORATORY

SOURCE : DESTINATION = WEIGHT

1 : 2 = 4

5 : 3 = 2

2 : 4 = 6

2 : 5 = 1

RESULT

Thus the implementation of Minimum Spanning Tree using Prims Algorithm has been
implemented and output has been verified.

VIVA VOICE
1. What is a spanning tree?
A spanning tree is a subset of Graph G, which has all the vertices covered with minimum
possible number of edges. A spanning tree does not have cycles and it can not be
disconnected

2. How many spanning trees can a graph has?


It depends on how connected the graph is. A complete undirected graph can have
maximum nn-1 number of spanning trees, where n is number of nodes.

3. How Prim's algorithm finds spanning tree?


Prim's algorithm treats the nodes as a single tree and keeps on adding new nodes to the
spanning tree from the given graph.

4. What is a minimum spanning tree (MST) ?


In a weighted graph, a minimum spanning tree is a spanning tree that has minimum
weight that all other spanning trees of the same graph.
5. How can you create minimum spanning tree using prim’s algorithm?
In Prim’s algorithm, for creating minimum spanning tree, start with any node and
include the other node in the spanning tree, on the basis of its weight of their
edges connected to that node, and move on until it includes all the n vertices are
connected by n-1 edges. The resulting tree contains all the vertices present in the
given graph, such that the weight of the edges in the resulting tree is minimum.
The tree produced by the above algorithm, is the minimum spanning tree.
6. Define the term Prim’s Algorithm.

M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 21
16CS311 - ALGORITHMS LABORATORY

In a graph a pair with the minimum weight is to be chosen. Then adjacent to


these vertices is the edge having minimum weight is selected ie., in each stage,
one node is picked as the root, then add an edge and thus an associated vertex to
the tree.
Exercise Number: 3(b)
Title of the Exercise: Kruskal’s Algorithm
--------------------------------------------------------------------------------------------------------------

OBJECTIVE OF THE EXPERIMENT


To create a simple java program to implement Minimum Spanning Tree using
Kruskals Algorithm.
DESCRIPTION
Start with an empty set A, and select at every stage the shortest edge that has not been
chosen or rejected,
regardless of where this edge is situated in graph.
Initially, each vertex is in its own tree in forest.
Then, algorithm considers each edge in turn, order by increasing weight.
If an edge (u, v) connects two different trees, then (u, v) is added to the set of edges of
the
MST, and two trees connected by an edge (u, v) are merged into a single tree.
On the other hand, if an edge (u, v) connects two vertices in the same tree, then edge (u,
v) is discarded.
Kruskals algorithm can be implemented using disjoint set data structure or priority
queue data structure.
Kruskal's algorithm implemented with disjoint-sets data structure.
Disjoint-Sets Data Structure
• Make_Set (v)
Create a new set whose only member is pointed to by v. Note that for this operation v
mustalready be in a set.
FIND_Set
Returns a pointer to the set containing v.
• UNION (u, v)
Unites the dynamic sets that contain u and v into a new set that is union of these two
sets

ALGORITHM
1. Sort all the edges in non-decreasing order of their weight.
2. Pick the smallest edge. Check if it forms a cycle with the spanning tree formed so far. If
cycle is not formed, include this edge. Else, discard it.
3. Repeat step#2 until there are (V-1) edges in the spanning tree.

M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 22
16CS311 - ALGORITHMS LABORATORY

PROGRAM
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);
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 23
16CS311 - ALGORITHMS LABORATORY

}
}
}
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++)
{
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 24
16CS311 - ALGORITHMS LABORATORY

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

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
{
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 25
16CS311 - ALGORITHMS LABORATORY

int sourcevertex;
int destinationvertex;
int weight;
}

class EdgeComparator implements Comparator<Edge>


{
@Override
public int compare(Edge edge1, Edge edge2)
{
if (edge1.weight < edge2.weight)
return -1;
if (edge1.weight > edge2.weight)
return 1;
return 0;
}
}

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];
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 26
16CS311 - ALGORITHMS LABORATORY

}
}

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;
}
i++;
}
stack.pop();
}
return cyclepresent;
}
}
OUTPUT
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 27
16CS311 - ALGORITHMS LABORATORY

Enter the number of vertices

Enter the Weighted Matrix for the graph

068600

6 0 0 5 10 0

800753

657000

0 10 5 0 0 3

003030

The spanning tree is

1 2 3 4 5 6

1 0 6 0 0 0 0

2 6 0 0 5 0 0

3 0 0 0 7 0 3

4 0 5 7 0 0 0

5 0 0 0 0 0 3

6 0 0 3 0 3 0

RESULT

Thus the implementation of Minimum Spanning Tree using Kruskal Algorithm has been
implemented and output has been verified.

M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 28
16CS311 - ALGORITHMS LABORATORY

VIVA VOICE

1. What is a spanning tree?


A spanning tree is a subset of Graph G, which has all the vertices covered with minimum
possible number of edges. A spanning tree does not have cycles and it can not be
disconnected

2. How many spanning trees can a graph has?


It depends on how connected the graph is. A complete undirected graph can have
maximum nn-1 number of spanning trees, where n is number of nodes.

3. How Kruskal's algorithm works?


This algorithm treats the graph as a forest and every node it as an individual tree. A tree
connects to another only and only if it has least cost among all available options and
does not violate MST properties.

4. What is a minimum spanning tree (MST) ?


In a weighted graph, a minimum spanning tree is a spanning tree that has minimum
weight that all other spanning trees of the same graph.

5. How can you create minimum spanning tree using Kruskal’s algorithm?
In Kruskal’s algorithm, for creating minimum spanning tree, sort the edges in the graph
on increasing order by its weight. Take the first edge from the ordered list and add the
source vertex to form a tree. Check whether the destination vertex to the tree. If it
already exists, move to the next edge in the ordered list. Repeat the steps until the tree
contains all the n vertices. The tree produced by the above algorithm, is the minimum
spanning tree.

6. List the applications of MST.


• Connecting of computers in the lab with the minimum length of wire.
• Telephone networking companies.
• It provides way for clustering points in space in to natural graphs.

M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 29
16CS311 - ALGORITHMS LABORATORY

Exercise Number: 4
Title of the Exercise: Implementation of Dijkstra’s Algorithm
---------------------------------------------------------------------------------------------------------------

OBJECTIVE OF THE EXPERIMENT


To write a java program to find the shortest path from source to all nodes using
dijikstra's algorithm in the given graph.

DESCRIPTION
Given a graph and a source vertex in graph, find shortest paths from source to all
vertices in the given graph.

Dijkstra’s algorithm is very similar to Prim’s algorithm for minimum spanning tree. Like
Prim’s MST, we generate a SPT (shortest path tree) with given source as root. We
maintain two sets, one set contains vertices included in shortest path tree, other set
includes vertices not yet included in shortest path tree. At every step of the algorithm,
we find a vertex which is in the other set (set of not yet included) and has minimum
distance from source.

Below are the detailed steps used in Dijkstra’s algorithm to find the shortest path from a
single source vertex to all other vertices in the given graph.

ALGORITHM
1. Declare all necessary variables and initialize those variables.
2. Get the number of vertices and adjacency matrix.
3. Get the source node and store it in source variable.
4. Create a object for the class DijikstraQueue to access the method dijikstra-algorithm.
5. In this method get the copy of the adjacency matrix. Add the source into the queue.
6. Access getNodewithMinimumDistanceFromQueue,in this get the minimum capacity
vertice and add it to the settle set.
7. Keeping the distance of the node,handle the neighbours of the source and add them to
the queue.After handling the source,remove it from queue.
8. Again handle the nodes that are in queue as the same steps that before we performed.

M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 30
16CS311 - ALGORITHMS LABORATORY

9. While queue is empty stop the process and then we get the shortest path.
10. Finally, the shortest path from source to each other node is return

PROGRAM
import java.util.HashSet;
import java.util.InputMismatchException;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
import java.util.Set;
public class DijkstraQueue
{
private int distances[];
private Queue<Integer> queue;
private Set<Integer> settled;
private int number_of_nodes;
private int adjacencyMatrix[][];
public DijkstraQueue(int number_of_nodes)
{
this.number_of_nodes = number_of_nodes;
distances = new int[number_of_nodes + 1];
settled = new HashSet<Integer>();
queue = new LinkedList<Integer>();
adjacencyMatrix = new int[number_of_nodes + 1][number_of_nodes + 1];
}
public void dijkstra_algorithm(int adjacency_matrix[][], int source)
{
int evaluationNode;
for (int i = 1; i <= number_of_nodes; i++)
for (int j = 1; j <= number_of_nodes; j++)
adjacencyMatrix[i][j] = adjacency_matrix[i][j];
for (int i = 1; i <= number_of_nodes; i++)
{MBCET ME/CSE ADVANCED DATA STRUCTURES LAB –CP7111
V.GOPALAKRISHNAN AP/CSE 23
distances[i] = Integer.MAX_VALUE;
}
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 31
16CS311 - ALGORITHMS LABORATORY

queue.add(source);
distances[source] = 0;
while (!queue.isEmpty())
{
evaluationNode = getNodeWithMinimumDistanceFromQueue();
settled.add(evaluationNode);
evaluateNeighbours(evaluationNode);
}
}
private int getNodeWithMinimumDistanceFromQueue()
{
int min ;
int node = 0;
Iterator<Integer> iterator = queue.iterator();
node = iterator.next();
min = distances[node];
for (int i = 1; i <= distances.length; i++)
{
if (queue.contains(i))
{
if (distances[i] <= min)
{
min = distances[i];
node = i;
}
}
}
queue.remove(node);
return node;
}
private void evaluateNeighbours(int evaluationNode)
{
int edgeDistance = -1;
int newDistance = -1;
for (int destinationNode = 1; destinationNode <= number_of_nodes;
destinationNode++)
{
if (!settled.contains(destinationNode))
{
if (adjacencyMatrix[evaluationNode][destinationNode] !=
Integer.MAX_VALUE)
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 32
16CS311 - ALGORITHMS LABORATORY

{
edgeDistance = adjacencyMatrix[evaluationNode][destinationNode];
newDistance = distances[evaluationNode] + edgeDistance;
if (newDistance < distances[destinationNode])
{
distances[destinationNode] = newDistance;
}
queue.add(destinationNode);
}
}
}
}
public static void main(String... arg)
{
int adjacency_matrix[][];
int number_of_vertices;
int source = 0;
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] = Integer.MAX_VALUE;
}
}
}
System.out.println("Enter the source ");
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 33
16CS311 - ALGORITHMS LABORATORY

source = scan.nextInt();
DijkstraQueue dijkstrasQueue = new DijkstraQueue(number_of_vertices);
dijkstrasQueue.dijkstra_algorithm(adjacency_matrix, source);
System.out.println("The Shorted Path to all nodes are ");
for (int i = 1; i <= dijkstrasQueue.distances.length - 1; i++)
{
System.out.println(source + " to " + i + " is " + dijkstrasQueue.distances[i]);
}
} catch (InputMismatchException inputMismatch)
{
System.out.println("Wrong Input Format");
}
scan.close();
}
}
OUTPUT

Enter the number of vertices

Enter the Weighted Matrix for the graph

07002

00102

00040

00500

03850

Enter the source

The Shorted Path to all nodes are

1 to 1 is 0

1 to 2 is 5

1 to 3 is 6

M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 34
16CS311 - ALGORITHMS LABORATORY

1 to 4 is 7

1 to 5 is 2

RESULT

Thus the java program to find shortest path from source to all nodes using dijikstra’s
algorithm in the given graph has been executed successfully and the output is verified..

VIVA VOICE
1: Given a directed weighted graph. You are also given the shortest path from a source
vertex ‘s’ to a destination vertex ‘t’. If weight of every edge is increased by 10 units, does
the shortest path remain same in the modified graph?
The shortest path may change. The reason is, there may be different number of edges in
different paths from s to t. For example, let shortest path be of weight 15 and has 5
edges. Let there be another path with 2 edges and total weight 25. The weight of the
shortest path is increased by 5*10 and becomes 15 + 50. Weight of the other path is
increased by 2*10 and becomes 25 + 20. So the shortest path changes to the other path
with weight as 45.

2: This is similar to above question. Does the shortest path change when weights of all
edges are multiplied by 10?
If we multiply all edge weights by 10, the shortest path doesn’t change. The reason is
simple, weights of all paths from s to t get multiplied by same amount. The number of
edges on a path doesn’t matter. It is like changing unit of weights.

3: Given a directed graph where every edge has weight as either 1 or 2, find the shortest
path from a given source vertex ‘s’ to a given destination vertex ‘t’. Expected time
complexity is O(V+E).
If we apply Dijkstra’s shortest path algorithm, we can get a shortest path in O(E +
VLogV) time. How to do it in O(V+E) time? The idea is to use BFS . One important
observation about BFS is, the path used in BFS always has least number of edges
between any two vertices. So if all edges are of same weight, we can use BFS to find the
shortest path. For this problem, we can modify the graph and split all edges of weight 2
into two edges of weight 1 each. In the modified graph, we can use BFS to find the
shortest path. How is this approach O(V+E)? In worst case, all edges are of weight 2 and
we need to do O(E) operations to split all edges, so the time complexity becomes O(E) +
O(V+E) which is O(V+E).

4.What is the use of Dijkstra’s algorithm?


Dijkstra’s algorithm is a greedy algorithm to find the minimum distance from a node to

M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 35
16CS311 - ALGORITHMS LABORATORY

all other nodes. Our aim is to visit any two nodes, with a minimum weight, such that the
distance travelled is minimum. One such algorithm is referred as Dijkstra’s shortest path
algorithm. This is very much used in travelling salesman problem

Exercise Number: 5
Title of the Exercise: Implementation of knapsack problem
---------------------------------------------------------------------------------------------------------------
OBJECTIVE OF THE EXPERIMENT
To create a simple java program to implement knapsack problem using greedy
algorithm.
DESCRIPTION
Given weights and values of n items, put these items in a knapsack of capacity W
to get the maximum total value in the knapsack. In other words, given two integer arrays
val[0..n-1] and wt[0..n-1] which represent values and weights associated with n items
respectively. Also given an integer W which represents knapsack capacity, find out the
maximum value subset of val[] such that sum of the weights of this subset is smaller
than or equal to W. You cannot break an item, either pick the complete item, or don’t
pick it (0-1 property).

A simple solution is to consider all subsets of items and calculate the total weight and
value of all subsets. Consider the only subsets whose total weight is smaller than W.
From all such subsets, pick the maximum value subset.

1) Optimal Substructure:
To consider all subsets of items, there can be two cases for every item: (1) the item is
included in the optimal subset, (2) not included in the optimal set.
Therefore, the maximum value that can be obtained from n items is max of following
two values.
1) Maximum value obtained by n-1 items and W weight (excluding nth item).
2) Value of nth item plus maximum value obtained by n-1 items and W minus weight of
the nth item (including nth item).

If weight of nth item is greater than W, then the nth item cannot be included and case 1
is the only possibility.

M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 36
16CS311 - ALGORITHMS LABORATORY

ALGORITHM
 Assume knapsack holds weight W and items have value vi and weight wi

 Rank items by value/weight ratio: vi / wi

o Thus: vi / wi ≥ vj / wj, for all i ≤ j

 Consider items in order of decreasing ratio

 Take as much of each item as possible

PROGRAM
import java.util.Scanner;

/** Class Knapsack **/


public class 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];
/** select max of m1, m2 **/
m[i][j] = Math.max(m1, m2);
sol[i][j] = m2 > m1 ? 1 : 0;
}
}
/** make list of what all items to finally select **/
int[] selected = new int[N + 1];
for (int n = N, w = W; n > 0; n--)
{
if (sol[n][w] != 0)
{
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 37
16CS311 - ALGORITHMS LABORATORY

selected[n] = 1;
w = w - wt[n];
}
else
selected[n] = 0;
}
/** Print finally selected items **/
System.out.println("\nItems selected : ");
for (int i = 1; i < N + 1; i++)
if (selected[i] == 1)
System.out.print(i +" ");
System.out.println();
}
/** Main function **/
public static void main (String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Knapsack Algorithm Test\n");
/** Make an object of Knapsack class **/
Knapsack ks = new 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("\nEnter weight for "+ n +" elements");


for (int i = 1; i <= n; i++)
wt[i] = scan.nextInt();
System.out.println("\nEnter value for "+ n +" elements");
for (int i = 1; i <= n; i++)
val[i] = scan.nextInt();

System.out.println("\nEnter knapsack weight ");


int W = scan.nextInt();

ks.solve(wt, val, W, n);


}
}

M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 38
16CS311 - ALGORITHMS LABORATORY

OUTPUT
Knapsack Algorithm Test

Enter number of elements


5

Enter weight for 5 elements


50 10 20 40 30

Enter value for 5 elements


300 60 90 100 240

Enter knapsack weight


60

Items selected :
235

M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 39
16CS311 - ALGORITHMS LABORATORY

RESULT
Thus the implementation of knapsack problem using greedy algorithm has been
implemented and output has been verified.

VIVA VOCE
1. Define Greedy method?
i. Greedy method is a popular method for obtaining optimized solutions. The
solution is constructed through a sequence of steps, each expanded in a partially
constructed solution obtained so far, until a complete solution to the problem is reached.
2. Applications of Greedy Method
Knapsack Problem
Prims Algorithm for Minimum Spanning tree.
Kruskal algorithm for Minimum Spanning tree.
Optimal Storage on tapes.
Job Sequencing With Deadlines.
3. What are the choices made by the greedy method?
Feasible i.e., it has to satisfy the problem’s constraints.
Locally optimal, i.e., it has to be the best local choice among all feasible choices available
on those steps.
Irrevocable i.e., once made, it cannot be changed on subsequent steps of the algorithm.
4. What is the objective of Knapsack problem?
i. The objective is to obtain a filling of the knapsack that maximizes the total profit
earned.
5. Define sensible greedy algorithm for knapsack problem?
i. A sensible greedy algorithm for the knapsack problem is based on processing an
input’s items in descending order of their value to weight ratios. For the continuous
version of the problem, this algorithm always yields an exact optimal solution.
6. Define greedy algorithm for the discrete knapsack problem?
Compute the value to weight ratios r=v/w for the items given
Sort the items in non-increasing order of the ratios computed in step1.
Repeat the following operation until no item is left in the sorted list if the current
item on the lists fits into the knapsack, place it in the knapsack otherwise proceed to the
next item.

M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 40
16CS311 - ALGORITHMS LABORATORY

7. Define greedy algorithm for the continuous knapsack problem?


Compute the value to weight ratios r=v/w for the items given
Sort the items in non-increasing order of the ratios computed in step1.
Repeat the following operation until the knapsack is filled to its full capacity or no item
is left in the sorted list if the current item on the lists fits into the knapsack in its entirely,
take it and proceed to the next item.

8.Check if all people can vote on two machines


There are n people and two identical voting machines. We are also given an array a[] of
size n such that a[i] stores time required by i-th person to go to any machine, mark his
vote and come back. At one time instant, only one person can be there on each of the
machines. Given a value x, defining the maximum allowable time for which machines are
operational, check whether all persons can cast their vote or not.

9.Unbounded Knapsack (Repetition of items allowed)


Given a knapsack weight W and a set of n items with certain value vali and weight wti,
we need to calculate minimum amount that could make up this quantity exactly. This is
different from classical Knapsack problem, here we are allowed to use unlimited
number of instances of an item.

M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 41
16CS311 - ALGORITHMS LABORATORY

Exercise Number: 6
Title of the Exercise: Computing transitive closure using warshall algorithm
---------------------------------------------------------------------------------------------------------------
OBJECTIVE OF THE EXPERIMENT
To create a java program to implement computing transitive closure using
warshall algorithm.
DESCRIPTION
Given a directed graph, find out if a vertex j is reachable from another vertex i for all
vertex pairs (i, j) in the given graph. Here reachable mean that there is a path from
vertex i to j. The reach-ability matrix is called transitive closure of a graph.

The graph is given in the form of adjacency matrix say ‘graph[V][V]’ where graph[i][j] is
1 if there is an edge from vertex i to vertex j or i is equal to j, otherwise graph[i][j] is 0.

Floyd Warshall Algorithm can be used, we can calculate the distance matrix dist[V][V]
using Floyd Warshall, if dist[i][j] is infinite, then j is not reachable from i, otherwise j is
reachable and value of dist[i][j] will be less than V.
Instead of directly using Floyd Warshall, we can optimize it in terms of space and time,
for this particular problem. Following are the optimizations:

1) Instead of integer resultant matrix (dist[V][V] in floyd warshall), we can create a


boolean reach-ability matrix reach[V][V] (we save space). The value reach[i][j] will be 1
if j is reachable from i, otherwise 0.

2) Instead of using arithmetic operations, we can use logical operations. For arithmetic
operation ‘+’, logical and ‘&&’ is used, and for min, logical or ‘||’ is used. (We save time by
a constant factor. Time complexity is same though)

ALGORITHM
• Accept no .of vertices

M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 42
16CS311 - ALGORITHMS LABORATORY

• Call graph function to read weighted graph // w(i,j)


• Set D[ ] <- weighted graph matrix // get D {d(i,j)} for k=0
• // If there is a cycle in graph, abort. How to find?
• Repeat for k = 1 to n
Repeat for i = 1 to n
Repeat for j = 1 to n
D[i,j] = min {D[i,j], D[i,k] + D[k,j]}
• Print D

PROGRAM
import java.util.Scanner;

/** Class Warshall **/


public class Warshall
{
private int V;
private boolean[][] tc;
/** Function to make the transitive closure **/
public void getTC(int[][] graph)
{
this.V = graph.length;
tc = new boolean[V][V];
for (int i = 0; i < V; i++)
{
for (int j = 0; j < V; j++)
if (graph[i][j] != 0)
tc[i][j] = true;
tc[i][i] = true;
}
for (int i = 0; i < V; i++)
{
for (int j = 0; j < V; j++)
{
if (tc[j][i])
for (int k = 0; k < V; k++)
if (tc[j][i] && tc[i][k])
tc[j][k] = true;
}
}
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 43
16CS311 - ALGORITHMS LABORATORY

}
/** Funtion to display the trasitive closure **/
public void displayTC()
{
System.out.println("\nTransitive closure :\n");
System.out.print(" ");
for (int v = 0; v < V; v++)
System.out.print(" " + v );
System.out.println();
for (int v = 0; v < V; v++)
{
System.out.print(v +" ");
for (int w = 0; w < V; w++)
{
if (tc[v][w])
System.out.print(" * ");
else
System.out.print(" ");
}
System.out.println();
}
}

/** Main function **/


public static void main (String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Warshall Algorithm Test\n");
/** Make an object of Warshall class **/
Warshall w = new Warshall();

/** Accept number of vertices **/


System.out.println("Enter number of vertices\n");
int V = scan.nextInt();

/** get graph **/


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();
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 44
16CS311 - ALGORITHMS LABORATORY

w.getTC(graph);
w.displayTC();
}
}

OUTPUT
Warshall Algorithm Test
Enter number of vertices

Enter matrix

010001
000000
100100
000000
000100
000010

Transitive closure :

0 1 2 3 4 5
0 * * * * *
1 *
2 * * * * * *
3 *
4 * *
5 * * *

M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 45
16CS311 - ALGORITHMS LABORATORY

RESULT
Thus the java program for computing transitive closure using warshall algorithm has
been implemented and output has been verified.

VIVA VOICE
1. Define transitive closure?
The transitive closure of a directed graph with n vertices can be defined as the n-
by-n Boolean matrix T = {tij}, in which the element in the ith row (1<= i <=n) and the jth
column (1<= j <=n) is 1 if there exists a nontrivial directed path from the ith vertex to
the jth vertex otherwise tij is 0.
2. Define warshall’s algorithm?
a. Wharshall’s algorithm constructs the transitive closure of a given digraph with n
vertices through a series of n-by-n Boolean matrices.
b. R (0)…, R (k-1), R (k)…, R (n)
c. Each of these matrices provides certain information about directed paths in the
digraph.
3. How a transitive closure can be generated?
i. Transitive closure can be generated using depth-first or breadth-first search.
Starting from ith vertex, it shows reachable vertices – thus fills the ith line in matrix
Doing so for each vertex as starting point give us a transitive closure matrix.
But it transverse whole digraph several times.
4. What is the rule for generating elements of matrix R (K) from R (k-1)?
a. If an element rij is 1 in R (K-1), it remains 1 in R (k).
b. If an element rij is 0 in R (k-1), it has to be changed to 1 in R (K) if and only if the
element in its row I and column K and the element K and the element in its column J and
row K are both 1’s in R (K-1).
5. What is the efficiency of warshall’s algorithm?
The efficiency of warshall’s algorithm shows that it can be applied to the more general
problem of finding length of the shortest path of the weighted graphs.
6.Define distance matrix?
The element dij in the ith row and the jth column of this matrix indicates the
length of the shortest path from the ith vertex to jth vertex (1<=i, j<=n).
7 . Define Floyd’s algorithm?
Floyd’s algorithm computes the distance matrix of weighted graph with n
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 46
16CS311 - ALGORITHMS LABORATORY

vertices through a series of n-by-n matrices


ii. D (O)…., D (K-1), D (K)…, D (n)
b. Each of these matrices contains the lengths of the shortest paths with certain
constraints on the paths considered for the matrix in question.
8. What is the time complexity of Floyd–Warshall algorithm to calculate all pair shortest
path in a graph with n vertices?
(A) O(n^2logn)
(B) Theta(n^2logn)
(C) Theta(n^4)
(D) Theta(n^3)
Answer: (D)
Exercise Number: 7
Title of the Exercise: Travelling salesperson using dynamic programming
---------------------------------------------------------------------------------------------------------------
OBJECTIVE OF THE EXPERIMENT
To write a java program to find the shortest path and minimum cost for travelling
salesperson problem.
DESCRIPTION
The travelling salesman problem (TSP) asks the following question: "Given a list of cities
and the distances between each pair of cities, what is the shortest possible route that
visits each city exactly once and returns to the origin city?" It is an NP-hard problem in
combinatorial optimization, important in operations research and theoretical computer
science.
The travelling purchaser problem and the vehicle routing problem are both
generalizations of TSP.
In the theory of computational complexity, the decision version of the TSP (where, given
a length L, the task is to decide whether the graph has any tour shorter than L) belongs
to the class of NP-complete problems. Thus, it is possible that the worst-case running
time for any algorithm for the TSP increases superpolynomially (but no more than
exponentially) with the number of cities.

The problem was first formulated in 1930 and is one of the most intensively studied
problems in optimization. It is used as a benchmark for many optimization methods.
Even though the problem is computationally difficult, a large number of heuristics and
exact algorithms are known, so that some instances with tens of thousands of cities can
be solved completely and even problems with millions of cities can be approximated
within a small fraction of 1

ALGORITHM
1. Declare all necessary variables and initialize those variables.

M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 47
16CS311 - ALGORITHMS LABORATORY

2. Create a object for the class TSP.


3. Get the number of nodes and weight of each edges.
4. The eval() method declares and initializes the dummyset array.
5. The cost() method finds the final cost by finding the cost of each path.
6. The constructor()method finds the path in terms of tour from the source node and
again it reaches the source.
7. From among all the tour paths the one with minimum cost is selected as the best
path.
8. Using display() method the tour path is return along with final cost as the result of
the travelling sales person problem

PROGRAM
import java.util.*;
import java.text.*;
class TSP
{
int weight[][],n,tour[],finalCost;
final int INF=1000;
public TSP()
{
Scanner s=new Scanner(System.in);
System.out.println("Enter no. of nodes:=>");
n=s.nextInt();
weight=new int[n][n];
tour=new int[n-1];
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(i!=j)
{
System.out.print("Enter weight of "+(i+1)+" to "+(j+1)+":=>");
weight[i][j]=s.nextInt();
}
}
}
System.out.println();
System.out.println("Starting node assumed to be node 1.");
eval();
}
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 48
16CS311 - ALGORITHMS LABORATORY

public int COST(int currentNode,int inputSet[],int setSize)


{
if(setSize==0)
return weight[currentNode][0];
int min=INF,minindex=0;
int setToBePassedOnToNextCallOfCOST[]=new int[n-1];
for(int i=0;i<setSize;i++)
{
int k=0;//initialise new set
for(int j=0;j<setSize;j++)
{
if(inputSet[i]!=inputSet[j])
setToBePassedOnToNextCallOfCOST[k++]=inputSet[j];
}
int temp=COST(inputSet[i],setToBePassedOnToNextCallOfCOST,setSize-1);
if((weight[currentNode][inputSet[i]]+temp) < min)
{
min=weight[currentNode][inputSet[i]]+temp;
minindex=inputSet[i];
}
}
return min;
}
public int MIN(int currentNode,int inputSet[],int setSize)
{
if(setSize==0)
return weight[currentNode][0];
int min=INF,minindex=0;
int setToBePassedOnToNextCallOfCOST[]=new int[n-1];
for(int i=0;i<setSize;i++)//considers each node of inputSet
{
int k=0;
for(int j=0;j<setSize;j++)
{
if(inputSet[i]!=inputSet[j])
setToBePassedOnToNextCallOfCOST[k++]=inputSet[j];
}
int temp=COST(inputSet[i],setToBePassedOnToNextCallOfCOST,setSize-1);
if((weight[currentNode][inputSet[i]]+temp) < min)
{
min=weight[currentNode][inputSet[i]]+temp;
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 49
16CS311 - ALGORITHMS LABORATORY

minindex=inputSet[i];
}
}
return minindex;
}
public void eval()
{
int dummySet[]=new int[n-1];
for(int i=1;i<n;i++)
dummySet[i-1]=i;
finalCost=COST(0,dummySet,n-1);
constructTour();
}
public void constructTour()
{
int previousSet[]=new int[n-1];
int nextSet[]=new int[n-2]; for(int i=1;i<n;i++)
previousSet[i-1]=i;
int setSize=n-1;
tour[0]=MIN(0,previousSet,setSize);
for(int i=1;i<n-1;i++)
{
int k=0;
for(int j=0;j<setSize;j++)
{
if(tour[i-1]!=previousSet[j])
nextSet[k++]=previousSet[j];
}
--setSize;
tour[i]=MIN(tour[i-1],nextSet,setSize);
for(int j=0;j<setSize;j++)
previousSet[j]=nextSet[j];
}
display();
}
public void display()
{
System.out.println();
System.out.print("The tour is 1-");
for(int i=0;i<n-1;i++)
System.out.print((tour[i]+1)+"-");
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 50
16CS311 - ALGORITHMS LABORATORY

System.out.print("1");
System.out.println();
System.out.println("The final cost is "+finalCost);
}
}
class TSPExp
{
public static void main(String args[])
{
TSP obj=new TSP();
}
}
OUTPUT
Enter number of nodes: 4
Enter weight of 1 to 2:5
Enter weight of 1 to 3:3
Enter weight of 1 to 4:14
Enter weight of 2 to 1:6
Enter weight of 2 to 3:5
Enter weight of 2 to 4:60
Enter weight of 3 to 1:2
Enter weight of 3 to 2:1
Enter weight of 3 to 4:7
Enter weight of 4 to 1:3
Enter weight of 4 to 2:32
Enter weight of 4 to 3:8
Starting node assumed to be node 1
The tour is 1-2-3-4-1
The final cost is 20

M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 51
16CS311 - ALGORITHMS LABORATORY

RESULT
Thus the travelling salesperson problem has been implemented and output has been
verified.

VIVA VOICE
1. What is difference between the dynamic programming and greedy method? NOV
2006
Difference between dynamic programming and greedy method is, it extends the
solution with the best possible decision (not all feasible decisions) at a algorithmic stage
based on the current local optimum and the best decision (not all possible decisions)
made in previous stage. It is not exhaustive, and does not give accurate answer to many
problems. But when it works, it will be the fastest method. The most popular greedy
algorithm is finding the minimal spanning tree as given by Kruskal.
2. Define dynamic programming? (Nov/Dec-2006)
When a problem shows an optimal substructure, i.e. when the optimal solution to
a problem consists of optimal solutions to sub problems (for instance the shortest path
between two vertices on a weighted graph consists of the shortest path between all the
vertices in between) you solve such a problem bottom-up by solving the simplest
problems until you have solved the original problem. This is called a dynamic
programming algorithm.
3. Define binomial coefficient?
The quantity (x + y)9 is binomial if we multiply out the binomial expansion (x + y)2 we
get x2 + 2xy +y2. The coefficients or numerical multipliers of successive terms in these
results are 1, 2, 1.
4. What is the efficiency of binomial algorithm?
The basic operation of this algorithm is addition so the total number of additions made
by this algorithm is based on computing coefficient.
5. What are the three components in dynamic programming solution?
Formulate the answer as a recurrence relation or recursive algorithm
Show that the number of different instances of your recurrence is bounded by a
polynomial.
Specify an order of evaluation for recurrence so you always have what you need.
6. Define the principle of optimality? (MAY/JUNE 06, NOV/DEC 06)
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 52
16CS311 - ALGORITHMS LABORATORY

i. Optimal solution to any instance of an optimization problem is composed of


optimal solutions to its sub instances.

Exercise Number: 8
Title of the Exercise: N Queens Problem
---------------------------------------------------------------------------------------------------------------
OBJECTIVE OF THE EXPERIMENT
To write a java program to place the N number of Queens in a N*N chess board.

DESCRIPTION
The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that
no two queens attack each other.
Given an integer n, return all distinct solutions to the n-queens puzzle.
Each solution contains a distinct board configuration of the n-queens' placement, where
'Q' and '.' both indicate a queen and an empty space respectively.

ALGORITHM
1. Declare all necessary variables and initialize those variables.
2. Get the number of Queens and store it in the variable N.
3. Call enumerate() method and create array a and initialize it.
4. By using the method overloading concept, the queens one by one.
5. Then by using is consistent method to check that no two queens should be placed in
the
diagonal or in same row or column.
6. Place the queens in the board by satisfying the conditions and mark the remaining
place as *.
7. Finally the output will display all the possible ways to place the queens in chess board

PROGRAM
import java.util.*;
public class Queens

M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 53
16CS311 - ALGORITHMS LABORATORY

{
public static boolean isConsistent(int[] q, int n)
{
for (int i = 0; i < n; i++)
{
if (q[i] == q[n]) return false; // same column
if ((q[i] - q[n]) == (n - i)) return false; // same major diagonal
if ((q[n] - q[i]) == (n - i)) return false; // same minor diagonal
}
return true;
}
public static void printQueens(int[] q)
{
int N = q.length;
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
if (q[i] == j) System.out.print("Q ");
else System.out.print("* ");
}
System.out.println();
}
System.out.println();
}
public static void enumerate(int N)
{
int[] a = new int[N];
enumerate(a, 0);
}
public static void enumerate(int[] q, int n)
{
int N = q.length;
if (n == N) printQueens(q);
else
{
for (int i = 0; i < N; i++)
{
q[n] = i;
if (isConsistent(q, n)) enumerate(q, n+1);
}
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 54
16CS311 - ALGORITHMS LABORATORY

}
}
public static void main(String args[])
{
Scanner S=new Scanner(System.in);
System.out.print("Enter no. of Queens: ");
int N = S.nextInt();
enumerate(N);
}
}

OUTPUT
Enter the number of elements in array
10
Enter 10 integer(s)
2
3
1
5
6
7
8
9
4
0
Enter the number to search
6
6 is present at location 5.

M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 55
16CS311 - ALGORITHMS LABORATORY

RESULT
Thus the java program for N queens problem has been implemented and output has
been verified.

VIVA VOICE
1) What is the algorithm that used to solve combinational problem?
 Back tracking
 Branch and bounding
2) Define back tracking?
Back tracking constructs its state space tree in the depth first search fashion in the
majority of its applications. If the sequence of choices represented by a current node of
the state space tree can be developed further without violating the problem’s
constraints, considering the first remaining legitimate option for the next component
does it.
3) Define the basic idea of backtracking.
The basic idea of backtracking is to build up a vector, one component at a time and to
test whether the vector being formed has any chance of success.
4) Define 8 queens problem?
Given a 8*8 chessboard and 8 queens we have to find a position for each queen such that
no queen may be taken by any another queen i.e., such that every row, column and
diagonal contains at most one queen
5) Define n queen’s problem?
The n queen’s problem is to place n queens on an n-by-n chessboard so that no two
queens attack each other by being in the same row or in the same column or in the same
diagonal.

M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 56
16CS311 - ALGORITHMS LABORATORY

Exercise Number: 9

Title of the Exercise: Graph coloring


---------------------------------------------------------------------------------------------------------------
OBJECTIVE OF THE EXPERIMENT
To write a java program to implement graph coloring using recursive backtracking
DESCRIPTION
In graph theory, graph coloring is a special case of graph labeling; it is an assignment of
labels traditionally called "colors" to elements of a graph subject to certain constraints.
In its simplest form, it is a way of coloring the vertices of a graph such that no two
adjacent vertices share the same color; this is called a vertex coloring. Similarly, an edge
coloring assigns a color to each edge so that no two adjacent edges share the same color,
and a face coloring of a planar graph assigns a color to each face or region so that no two
faces that share a boundary have the same color.

Vertex coloring is the starting point of the subject, and other coloring problems can be
transformed into a vertex version. For example, an edge coloring of a graph is just a
vertex coloring of its line graph, and a face coloring of a plane graph is just a vertex
coloring of its dual. However, non-vertex coloring problems are often stated and studied
as is. That is partly for perspective, and partly because some problems are best studied
in non-vertex form, as for instance is edge coloring.

The convention of using colors originates from coloring the countries of a map, where
each face is literally colored. This was generalized to coloring the faces of a graph
embedded in the plane. By planar duality it became coloring the vertices, and in this
form it generalizes to all graphs. In mathematical and computer representations, it is
typical to use the first few positive or nonnegative integers as the "colors". In general,

M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 57
16CS311 - ALGORITHMS LABORATORY

one can use any finite set as the "color set". The nature of the coloring problem depends
on the number of colors but not on what they are.
ALGORITHM
1. Get the number of vertices and store it in the variable n.
2. Create adjacency matrix,using for loop defines edges between the nodes are present
or not.
3. Get the number of colors available and store it in the variable m.
4. mcolouring() method calls another method nextvalue().
5. This method checks the next node value, here nodes are arranged as per the number
of colors available.
6. No two nodes have the same color nearly.
7. For n number of nodes the solution of the graph coloring is displayed.
8. If no solutions are present for the given input then it displays no possible solutions.

PROGRAM
import java.util.Scanner;
public class GraphColoring
{
private int V, numOfColors;
private int[] color;
private int[][] graph;

/** Function to assign color **/


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();
}
}
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 58
16CS311 - ALGORITHMS LABORATORY

/** function to assign colors recursively **/


public void solve(int v) throws Exception
{
/** base case - solution found **/
if (v == V)
throw new Exception("Solution found");
/** try all colours **/
for (int c = 1; c <= numOfColors; c++)
{
if (isPossible(v, c))
{
/** assign and proceed with next vertex **/
color[v] = c;
solve(v + 1);
/** wrong assignement **/
color[v] = 0;
}
}
}
/** function to check if it is valid to allot that color to vertex **/
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;
}
/** display solution **/
public void display()
{
System.out.print("\nColors : ");
for (int i = 0; i < V; i++)
System.out.print(color[i] +" ");
System.out.println();
}
/** Main function **/
public static void main (String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Graph Coloring Algorithm Test\n");
/** Make an object of GraphColoring class **/
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 59
16CS311 - ALGORITHMS LABORATORY

GraphColoring gc = new GraphColoring();

/** Accept number of vertices **/


System.out.println("Enter number of verticesz\n");
int V = scan.nextInt();

/** get graph **/


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
Enter the Number of Vertices
10

Enter matrix

0100010000
1010001000
0101000100
0010100010
1001000001
1000000110
0100000011
0010010001
0001011000
0000101100

Enter number of colors


3

Solution exists

M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 60
16CS311 - ALGORITHMS LABORATORY

Colors : 1 2 1 2 3 2 1 3 3 2

RESULT
Thus the Java program for graph coloring has been implemented and output has been
verified.

VIVA VOICE

1. Define graph coloring?


For graph, find its chromatic number i.e. the smallest number of colors that needs to be
assigned to the graph’s vertices so that no adjacent vertices are assigned the same color.
2. Define branch and bound?
Branch and bound is an algorithm design technique that enhances the idea of generating
a state space tree with the idea of estimating the best value obtainable from a current
node of the decision tree.
3. Define the Hamiltonian circuit.
The Hamiltonian is defined as a cycle that passes through all the vertices of the graph
exactly once. It is a sequence of n+1 adjacent vertices vi0, vi1,……, vin-1, vi0 where the
first vertex of the sequence is same as the last one while all the other n-1 vertices are
distinct.
4. What does assignment problem mean?
Assignment problem is a problem of assigning n peoples to n jobs so that the total cost
of the assignment is as small as possible.
5. What are the advantages of bounding?
Bounding functions are used to avoid the generations of sub trees that do not contain an
answer node.
6. What are the data structures found in branch and bound?
 First in first out
 Last in first out
7. Define Hamiltonian circuit problem?
Hamiltonian circuit means a path that starts and ends at the same vertex and passes
through all other vertices exactly once.

M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 61
16CS311 - ALGORITHMS LABORATORY

Exercise Number: 10
Title of the Exercise: Subset generation
---------------------------------------------------------------------------------------------------------------
OBJECTIVE OF THE EXPERIMENT
To create a simple java program to implement subset generation.
DESCRIPTION
A subset describes a selection of objects, where the order among them does not matter.
Many of the algorithmic problems in this catalog seek the best subset of a group of
things: vertex cover seeks the smallest subset of vertices to touch each edge in a graph;
knapsack seeks the most profitable subset of items of bounded total size; and set
packing seeks the smallest subset of subsets that together cover each item exactly once.

There are 2 power n subsets of an n-element set, including the empty set as well as the
set itself. This grows exponentially, but at a considerably smaller rate than the n!
permutations of n items. Indeed, since 2 power, a brute-force search through all subsets
of 20 elements is easily manageable, although by n=30 equls 1,073,741,824, so you will
certainly be pushing things.

By definition, the relative order among the elements does not distinguish different
subsets. Thus {125} power is the same as {215} . However, it is a very good idea to
maintain your subsets in a sorted or canonical order, in order to speed up such
operations as testing whether two subsets are identical or making them look right when
printed.

ALGORITHM
Algorithm SumOfSub (s, k, r)

M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 62
16CS311 - ALGORITHMS LABORATORY

//Values of x[ j ], 1 <= j < k, have been determined


//Node creation at level k taking place: also call for creation at level K+1 if possible
// s = sum of 1 to k-1 elements and r is sum of k to n elements
//generating left child that means including k in solution
• Set x[k] = 1
• If (s + s[k] = d) then subset found, print solution
• If (s + s[k] + s[k+1] <=d)
then SumOfSum (s + s[k], k+1, r – s[k])
//Generate right child i.e. element k absent
• If (s + r - s[k] >=d) AND (s + s[k+1] )<=d
THEN { x[k]=0;
SumOfSub(s, k+1, r – s[k])

PROGRAM
import static java.lang.Math.pow;
public class subSet {
/**
* @param args
*/
void subset(int num,int n, int x[])
{
int i;
for(i=1;i<=n;i++)
x[i]=0;
for(i=n;num!=0;i--)
{
x[i]=num%2;
num=num/2;
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int a[]=new int[10];
int x[]=new int[10];
int n,d,sum,present=0;
int j;
System.out.println("enter the number of elements of set");
Scanner sc=new Scanner(System.in);
n=sc.nextInt();
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 63
16CS311 - ALGORITHMS LABORATORY

System.out.println("enter the elements of set");


for(int i=1;i<=n;i++)
a[i]=sc.nextInt();
System.out.println("enter the positive integer sum");
d=sc.nextInt();
if(d>0)
{
for(int i=1;i<=Math.pow(2,n)-1;i++)
{
subSet s=new subSet();
s.subset(i,n,x);
sum=0;
for(j=1;j<=n;j++)
if(x[j]==1)
sum=sum+a[j];
if(d==sum)
{
System.out.print("Subset={");
present=1;
for(j=1;j<=n;j++)
if(x[j]==1)
System.out.print(a[j]+",");

System.out.print("}="+d);
System.out.println();
}

}
if(present==0)
System.out.println("Solution does not exists");

}
}
OUTPUT
enter the number of elements of set
5
enter the elements of set
12568
enter the positive integer sum
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 64
16CS311 - ALGORITHMS LABORATORY

9
Subset={1,8,}=9
Subset={1,2,6,}=9

RESULT
Thus the java program for subset generation has been implemented and output has
been verified.

VIVA VOICE
1. Define subset sum problem?
Subset sum 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. For example s= {1, 2, 6} and {1,
8}
2. What is the subset-sum problem?
Find a subset of a given set S= {s1,………, sn} of ‘n’ positive integers whose sum is equal
to a given positive integer‘d’.

3. What are the tricks used to reduce the size of the state-space tree?
The various tricks are.
1. Exploit the symmetry often present in combinatorial problems. So some solutions can
be obtained by the reflection of others. This cuts the size of the tree by about half.
2. Reassign values to one or more components of a solution.
3. Rearranging the data of a given instance.

4. How will you terminate a search path in a state space of a branch and bound
algorithm? (NOV/DEC 2009)
 The value of the node’s bound is not better than the value of the best solution
seen so for
 The node represents no feasible solutions because the constrains of the problem
are already violated
 The subset of the feasible solutions represented by the node consists of a single
point
5. Define state space tree?
State space tree is a tree in which the root represents an initial state before the search
M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 65
16CS311 - ALGORITHMS LABORATORY

begins. The node in the first level in the tree represent the choices made for the first
component of a solution, the nodes of the second level represent the choices for the
second component and so on.
6. What does promising mean?
A node in a state space tree is said to be promising if it corresponds to a partially
constructed solution that may still lead to a complete solution.
7. What are the branch and bound techniques that can be best fit?
a. Traveling salesman problem
b. Knapsack problem
8. Where the backtracking technique can be best fit?
a. N – queen problem
b. Hamiltonian problem
c. Subset problem

9. How can we tell which of the nodes is most promising?


By comparing the lower bounds of the live nodes we can tell whether the node is not
most promising or not.
10. Define live node?
A node, which has been generated, and all whose children have not yet been generated
is live node.

11. Define dead node?


A dead node is a generated node, which is not to be expanded further, or all of whose
children have been generated.

M KC E - D E PA RT M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G Page 66

S-ar putea să vă placă și