You are on page 1of 61

MAHARANA PRATAP COLLEGE

OF
Technology

ANALYSIS &DESIGN OF ALGORITHM


(CS-228)

PRACTICAL FILE

for

4thSemester

Submitted To: - Submitted By: -


Aarti Gupta Akash Pathak
(Asst. Professor) B.E. (computer science)
Dept. of Computer Science 0903CS151004
& Engineering
INDEX

S.NO PROGRAM PAGE NO. Date of Teacher


submission sign

1 Write a program for Iterative and Recursive Binary 2-4


Search.

2 Write a program for Merge Sort. 5-8

3 Write a program for Quick Sort. 9-11

4 Write a program for Strassen’s Matrix Multiplication. 12-18

5 Write a program for optimal merge patterns 19-22

6 Write a program for Huffman coding. 23-29

7 Write a program for minimum spanning trees using 30-38


Kruskal’s algorithm.

8 Write a program for minimum spanning trees using 39-41


Prim’s algorithm.

9 Write a program for single sources shortest path 42-45


algorithm.

10 Write a program for Floyd-Warshall algorithm. 46-50

11 Write a program for traveling salesman problem. 51-55

12 Write a program for Hamiltonian cycle problem. 56-60

1|Page
1.Write a program for iterative and Recursive Binary Search.
import java.util.Scanner;

class BinarySearchRecursive

public static void main(String[] args)

Scanner kb= new Scanner(System.in);

System.out .println("Welcome to perform binary search on int array");

System.out.println("Enter total number of elements : ");

int length = kb.nextInt();

int[] input = new int[length];

System.out.printf("Enter %d integers %n", length);

for (int i = 0; i < length; i++)

input[i] = kb.nextInt();

System.out .println("Please enter number to be searched in array (sorted order)");

int key = kb.nextInt();

int index = recursiveBinarySearch(input, key);

if (index == -1)

System.out.printf("Sorry, %d is not found in array %n", key);

else

2|Page
System.out.printf("%d is found in array at index %d %n", key, index);

kb.close();

public static int recursiveBinarySearch(int[] input, int key)

return binarySearch(input, 0, input.length - 1, key); }

private static int binarySearch(int[] array, int start, int end, int target)

int middle = (start + end) / 2;

if (end < start)

{ return -1; }

if (target == array[middle])

{ return middle; }

else if

(target < array[middle])

{ return binarySearch(array, start, middle - 1, target); }

else

{ return binarySearch(array, middle + 1, end, target);

3|Page
4|Page
2. Write a program for Merge Sort.
import java.util.*;

class MergeSort

public int a[]=new int[50];

public void merge_sort(int low,int high)

int mid;

if(low<high)

mid=(low+high)/2;

merge_sort(low,mid);

merge_sort(mid+1,high);

merge(low,mid,high);

public void merge(int low,int mid,int high)

int h,i,j,k;

int b[]=new int[50];

h=low;

i=low;

j=mid+1;

while((h<=mid)&&(j<=high))

5|Page
if(a[h]<=a[j])

b[i]=a[h];

h++;

else

b[i]=a[j];

j++;

i++;

if(h>mid)

for(k=j;k<=high;k++)

b[i]=a[k];

i++;

else

for(k=h;k<=mid;k++)

b[i]=a[k];

6|Page
i++; } }

for(k=low;k<=high;k++) a[k]=b[k];}

public MergeSort()

int num,i;

System.out.println("MERGE SORT PROGRAM");

System.out.println();

System.out.println();

System.out.println("Please Enter THE No. OF ELEMENTS you want to sort[THEN PRESS ENTER]:");

num=new Scanner(System.in).nextInt();

System.out.println();

System.out.println("Now, Please Enter the ("+ num +") nos. [THEN PRESS ENTER]:");

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

{ a[i]=new Scanner(System.in).nextInt() ; }

merge_sort(1,num);

System.out.println();

System.out.println("So, the sorted list (using MERGE SORT) will be :");

System.out.println();

System.out.println();

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

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

public static void main(String[] args) {

new MergeSort();

}}

7|Page
8|Page
3. Write a program for Quick Sort.
import java.util.Scanner;

class QuickSort

public static void sort(int[] arr)

quickSort(arr, 0, arr.length - 1);

public static void quickSort(int arr[], int low, int high)

int i = low, j = high;

int temp;

int pivot = arr[(low + high) / 2];

while (i <= j)

while (arr[i] < pivot)

i++;

while (arr[j] > pivot)

j--;

if (i <= j)

temp = arr[i];

arr[i] = arr[j];

arr[j] = temp;

9|Page
i++;

j--; } }

if (low < j)

{ quickSort(arr, low, j);}

if (i < high)

{ quickSort(arr, i, high); }

public static void main(String[] args)

{ Scanner scan = new Scanner( System.in );

System.out.println("Quick Sort Test\n");

int n, i;

System.out.println("Enter number of integer elements");

n = scan.nextInt();

int arr[] = new int[ n ];

System.out.println("\nEnter "+ n +" integer elements");

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

{ arr[i] = scan.nextInt();

sort(arr);

System.out.println("\nElements after sorting ");

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

{ System.out.print(arr[i]+" ");

System.out.println();

}}

10 | P a g e
11 | P a g e
4. Write a program for Strassen’s Matrix Multiplication.

import java.io.*;

class Strassen

public static BufferedReader br =new BufferedReader(new InputStreamReader(System.in));

public Strassen() throws IOException

int n;

int[][] a, b, c;

System.out.print("Enter the number or rows or colums: ");

n = Integer.parseInt(br.readLine());

a = new int[n][n];

b = new int[n][n];

c = new int[n][n];

System.out.print("\n\n\nEnter values for 1st Matrix:\n\n");

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

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

System.out.print("Enter the value of cell("+(i+1)+","+(j+1)+"): ");

a[i][j] = Integer.parseInt(br.readLine());

12 | P a g e
System.out.print("\n\n\5nEnter values for 2nd Matrix:\n");

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

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

System.out.print("Enter the value of cell ("+(i+1)+","+(j+1)+"): ");

b[i][j] = Integer.parseInt(br.readLine());

System.out.print("\n\nBy Strassen Matrix Multiplication method:\n");

c = strassenMatrixMultiplication(a, b);

printArray(c);

public int [][] strassenMatrixMultiplication(int [][] A, int [][] B)

int n = A.length;

int [][] result = new int[n][n];

if((n%2 != 0 ) && (n !=1))

int[][] a1, b1, c1;

int n1 = n+1;

a1 = new int[n1][n1];

b1 = new int[n1][n1];

c1 = new int[n1][n1];

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

13 | P a g e
for(int j=0; j<n; j++)

a1[i][j] =A[i][j];

b1[i][j] =B[i][j];

c1 = strassenMatrixMultiplication(a1, b1);

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

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

result[i][j] =c1[i][j];

return result;

if(n == 1)

result[0][0] = A[0][0] * B[0][0];

else

int [][] A11 = new int[n/2][n/2];

int [][] A12 = new int[n/2][n/2];

int [][] A21 = new int[n/2][n/2];

int [][] A22 = new int[n/2][n/2];

int [][] B11 = new int[n/2][n/2];

int [][] B12 = new int[n/2][n/2];

int [][] B21 = new int[n/2][n/2];

int [][] B22 = new int[n/2][n/2];

14 | P a g e
divideArray(A, A11, 0 , 0);

divideArray(A, A12, 0 , n/2);

divideArray(A, A21, n/2, 0);

divideArray(A, A22, n/2, n/2);

divideArray(B, B11, 0 , 0);

divideArray(B, B12, 0 , n/2);

divideArray(B, B21, n/2, 0);

divideArray(B, B22, n/2, n/2);

int [][] P1 = strassenMatrixMultiplication(addMatrices(A11, A22), addMatrices(B11, B22));

int [][] P2 = strassenMatrixMultiplication(addMatrices(A21, A22), B11);

int [][] P3 = strassenMatrixMultiplication(A11, subtractMatrices(B12, B22));

int [][] P4 = strassenMatrixMultiplication(A22, subtractMatrices(B21, B11));

int [][] P5 = strassenMatrixMultiplication(addMatrices(A11, A12), B22);

int [][] P6 = strassenMatrixMultiplication(subtractMatrices(A21, A11), addMatrices(B11, B12));

int [][] P7 = strassenMatrixMultiplication(subtractMatrices(A12, A22), addMatrices(B21, B22));

int [][] C11 = addMatrices(subtractMatrices(addMatrices(P1, P4), P5), P7);

int [][] C12 = addMatrices(P3, P5);

int [][] C21 = addMatrices(P2, P4);

int [][] C22 = addMatrices(subtractMatrices(addMatrices(P1, P3), P2), P6);

copySubArray(C11, result, 0 , 0);

copySubArray(C12, result, 0 , n/2);

copySubArray(C21, result, n/2, 0);

copySubArray(C22, result, n/2, n/2);

return result;

15 | P a g e
}

public int [][] addMatrices(int [][] A, int [][] B)

int n = A.length;

int [][] result = new int[n][n];

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

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

result[i][j] = A[i][j] + B[i][j];

return result;

public int [][] subtractMatrices(int [][] A, int [][] B)

int n = A.length;

int [][] result = new int[n][n];

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

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

result[i][j] = A[i][j] - B[i][j];

return result;

public void divideArray(int[][] parent, int[][] child, int iB, int jB)

for(int i1 = 0, i2=iB; i1<child.length; i1++, i2++)

for(int j1 = 0, j2=jB; j1<child.length; j1++, j2++)

child[i1][j1] = parent[i2][j2]; } }

16 | P a g e
public void copySubArray(int[][] child, int[][] parent, int iB, int jB)

for(int i1 = 0, i2=iB; i1<child.length; i1++, i2++)

for(int j1 = 0, j2=jB; j1<child.length; j1++, j2++)

parent[i2][j2] = child[i1][j1];

public void printArray(int [][] array)

int n = array.length;

System.out.println();

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

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

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

System.out.println();

System.out.println();

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

new Strassen(); } }

17 | P a g e
18 | P a g e
5. Write a program for optimal merge patterns.
#include<iostream>

using namespace std;

int main()

int i, k, Elements[20], cost[20], n, length;

cout<<"How many elements are there in a record?: ";

cin>>n;

cout<<"\nElements for optimal merge pattern in ascending order: ";

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

cin>>Elements[i];

cost[i] = 0;

i = 0;

k = 0;

cost[k] = Elements[i] + Elements[i+1];

i = 2;

while(i < n)

k++;

if((cost[k-1] + Elements[i]) <= (Elements[i] + Elements[i+1]))

cost[k] = cost[k-1] + Elements[i];

19 | P a g e
else

cost[k] = Elements[i] + Elements[i+1];

i = i + 2;

while(i < n)

k++;

if((cost[k-1] + Elements[i]) <= (cost[k-2] + Elements[i]))

cost[k] = cost[k-1] + Elements[i];

else

cost[k] = cost[k-2] + Elements[i];

i++;

i++;

k++;

cost[k] = cost[k-1] + cost[k-2];

cout<<"\n\nThe optimal sum are...\n";

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

20 | P a g e
cout<<cost[k]<<" ";

length = 0;

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

length = length + cost[k];

cout<<"\n\nThe total length is..."<<length;

21 | P a g e
22 | P a g e
6. Write a program for Huffman coding.
import java.util.ArrayList;

class Huffmancode

{ static Node node;

static Node newRoot;

static String codedString = "";

public static void main(String[] args)

{ String message = "MISSISSIPPI RIVER";

char[] msgChar = message.toCharArray();

ArrayList<Character> characters = new ArrayList<Character>();

for (int i = 0; i < msgChar.length; i++)

{ if (!(characters.contains(msgChar[i])))

{ characters.add(msgChar[i]);

} }

int[] countOfChar = new int[characters.size()];

for (int x = 0; x < countOfChar.length; x++)

{ countOfChar[x] = 0; }

for (int i = 0; i <characters.size(); i++)

{ char checker = characters.get(i);

for (int x = 0; x < msgChar.length; x++) {

if (checker == msgChar[x])

{ countOfChar[i]++; }

}}

for (int i = 0; i < countOfChar.length - 1; i++) {

23 | P a g e
for (int j = 0; j < countOfChar.length - 1; j++) {

if (countOfChar[j] <countOfChar[j + 1]) {

int temp = countOfChar[j];

countOfChar[j] = countOfChar[j + 1];

countOfChar[j + 1] = temp;

char tempChar = characters.get(j);

characters.set(j, characters.get(j + 1));

characters.set(j + 1, tempChar);

} } }

for (int x = 0; x < countOfChar.length; x++)

{ System.out.println(characters.get(x) + " - " + countOfChar[x]); }

Node root = null;

Node current = null;

Node end = null;

for (int i = 0; i < countOfChar.length; i++) {

Node node = new Node(characters.get(i).toString(), countOfChar[i]);

if (root == null) {

root = node;

end = node;

} else {

current = root;

while (current.linker != null) {

current = current.linker;

24 | P a g e
current.linker = node;

current.linker.linkerBack = current;

end = node;

TreeMaker(root, end);

System.out.println();

inOrder(node);

System.out.println();

preOrder(node);

char[] messageArray = message.toCharArray();

char checker;

for (int i = 0; i < messageArray.length; i++) {

current = node;

checker = messageArray[i];

String code = "";

while (true) {

if (current.left.value.toCharArray()[0] == checker) {

code += "0";

break;

} else {

code += "1";

if (current.right != null) {

if (current.right.value.toCharArray()[0] == characters

.get(countOfChar.length - 1)) {

25 | P a g e
break;

current = current.right;

} else {

break;

codedString += code;

System.out.println();

System.out.println("The coded string is " + codedString);

public static void preOrder(Node root) {

if (root != null) {

System.out.print(root.value + "->");

preOrder(root.left);

preOrder(root.right);

26 | P a g e
public static void inOrder(Node root) {

if (root != null) {

inOrder(root.left);

System.out.print(root.value + "->");

inOrder(root.right);

} }

public static void TreeMaker(Node root, Node end) {

node = new Node(end.linkerBack.value + end.value, end.linkerBack.count

+ end.count);

node.left = end.linkerBack;

node.right = end;

end.linkerBack.linkerBack.linker = node;

node.linkerBack = end.linkerBack.linkerBack;

end = node;

end.linker = null;

Node current = root;

while (current.linker != null)

System.out.print(current.value + "->");

current = current.linker;

System.out.println(current.value);

27 | P a g e
if (root.linker == end) {

node = new Node(root.value + end.value, root.count + end.count);

node.left = root;

node.right = end;

node.linker = null;

node.linkerBack = null;

System.out.println(node.value);

newRoot = node; }

else

{ TreeMaker(root, end);

} } }

class Node

{ String value;

int count;

Node left;

Node right;

Node linker;

Node linkerBack;

Node(String value, int count) {

this.value = value;

this.count = count;

this.left = null;

this.right = null;

this.linker = null;

this.linkerBack = null; )}

28 | P a g e
29 | P a g e
7. Write a program for minimum spanning trees using Kruskal’s
algorithm.
import java.util.Collections;

import java.util.Comparator;

import java.util.LinkedList;

import java.util.List;

import java.util.Scanner;

import java.util.Stack;

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

30 | P a g e
public void kruskalAlgorithm(int adjacencyMatrix[][])

boolean finished = false;

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

for (int destination = 1; destination <= numberOfVertices; destination++)

if (adjacencyMatrix[source][destination] != MAX_VALUE && source != destination)

Edge edge = new Edge();

edge.sourcevertex = source;

edge.destinationvertex = destination;

edge.weight = adjacencyMatrix[source][destination];

adjacencyMatrix[destination][source] = MAX_VALUE;

edges.add(edge);

Collections.sort(edges, new EdgeComparator());

CheckCycle checkCycle = new CheckCycle();

for (Edge edge : edges)

spanning_tree[edge.sourcevertex][edge.destinationvertex] = edge.weight;

spanning_tree[edge.destinationvertex][edge.sourcevertex] = edge.weight;

if (checkCycle.checkCycle(spanning_tree, edge.sourcevertex))

31 | P a g e
{

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

32 | P a g e
for (int source = 1; source <= numberOfVertices; source++)

System.out.print(source + "\t");

for (int destination = 1; destination <= numberOfVertices; destination++)

System.out.print(spanning_tree[source][destination] + "\t");

System.out.println();

public static void main(String... arg)

int adjacency_matrix[][];

int number_of_vertices;

Scanner scan = new Scanner(System.in);

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

number_of_vertices = scan.nextInt();

adjacency_matrix = new int[number_of_vertices + 1][number_of_vertices + 1];

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

33 | P a g e
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>

@Override

34 | P a g e
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++)

35 | P a g e
{

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)

36 | P a g e
stack.push(i);

visited[i] = 1;

adjacencyMatrix[element][i] = 0;

adjacencyMatrix[i][element] = 0;

element = i;

i = 1;

continue;

i++;

stack.pop();

return cyclepresent;

}}

37 | P a g e
38 | P a g e
8. Write a program for minimum spanning trees using Prim’s
algorithm
import java.util.*;

class Prims

public int isVisited[] = new int[15];

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

public int minimum_cost;

public void calc(int n)

int flag[] = new int[n+1];

int i,j,min=999,num_edges=1,a=1,b=1,minpos_i=1,minpos_j=1;

while(num_edges < n)

for(i=1,min=999;i<=n;i++)

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

if(this.cost[i][j]<min)

if(this.isVisited[i]!=0)

min=this.cost[i][j];

a=minpos_i=i;

b=minpos_j=j;

if(this.isVisited[minpos_i]==0 || this.isVisited[minpos_j]==0)

39 | P a g e
System.out.println("Edge Number \t"+num_edges+"\t from Vertex \t"+a+"\t to Vertex \t"+b+"-
mincost:"+min+" \n");

this.minimum_cost=this.minimum_cost+min;

num_edges=num_edges+1;

this.isVisited[b]=1;

this.cost[a][b]=this.cost[b][a]=999;

public static void main(String args[])

int nodes,i,j;

Scanner in = new Scanner(System.in);

System.out.println("Enter the Number of Nodes \n");

nodes = in.nextInt();

Prims p = new Prims();

System.out.println("Enter the Cost Matrix Weights : \n");

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

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

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

if(p.cost[i][j]==0)

p.cost[i][j]=999;}

p.isVisited[1]=1;

p.calc(nodes); } }

40 | P a g e
41 | P a g e
9. write a program for single sources shortest path algorithm.

import java.util.*;

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)

42 | P a g e
{

minimum=this.distance[i];

minpos=k;

flag[minpos]=1;

c++;

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

if(this.distance[minpos]+this.cost[minpos][k] < this.distance[k] && flag[k]!=1 )

this.distance[k]=this.distance[minpos]+this.cost[minpos][k];

public static void main(String args[])

int nodes,source,i,j;

Scanner in = new Scanner(System.in);

System.out.println("Enter the Number of Nodes \n");

nodes = in.nextInt();

Dijkstra d = new Dijkstra();

System.out.println("Enter the Cost Matrix Weights: \n");

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

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

43 | P a g e
{

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

44 | P a g e
45 | P a g e
10. write a program for Floyd Warshall algorithm.
import java.util.Scanner;

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

46 | P a g e
{

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

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

47 | P a g e
}

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)

48 | P a g e
{

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

49 | P a g e
50 | P a g e
11. Write a program for traveling salesman problem.

import java.util.InputMismatchException;

import java.util.Scanner;

import java.util.Stack;

class TSPNearestNeighbour

private int numberOfNodes;

private Stack<Integer> stack;

public TSPNearestNeighbour()

stack = new Stack<Integer>();

public void tsp(int adjacencyMatrix[][])

numberOfNodes = adjacencyMatrix[1].length - 1;

int[] visited = new int[numberOfNodes + 1];

visited[1] = 1;

stack.push(1);

int element, dst = 0, i;

int min = Integer.MAX_VALUE;

51 | P a g e
boolean minFlag = false;

System.out.print(1 + "\t");

while (!stack.isEmpty())

element = stack.peek();

i = 1;

min = Integer.MAX_VALUE;

while (i <= numberOfNodes)

if (adjacencyMatrix[element][i] > 1 && visited[i] == 0)

if (min > adjacencyMatrix[element][i])

min = adjacencyMatrix[element][i];

dst = i;

minFlag = true;

i++;

if (minFlag)

visited[dst] = 1;

stack.push(dst);

52 | P a g e
System.out.print(dst + "\t");

minFlag = false;

continue;

stack.pop();

public static void main(String... arg)

int number_of_nodes;

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

53 | P a g e
}

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

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

if (adjacency_matrix[i][j] == 1 && adjacency_matrix[j][i] == 0)

adjacency_matrix[j][i] = 1;

System.out.println("the citys are visited as follows");

TSPNearestNeighbour tspNearestNeighbour = new TSPNearestNeighbour();

tspNearestNeighbour.tsp(adjacency_matrix);

} catch (InputMismatchException inputMismatch)

System.out.println("Wrong Input format");

scanner.close();

54 | P a g e
55 | P a g e
12. Write a program for Hamiltonian cycle problem.
import java.util.Scanner;

import java.util.Arrays;

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

56 | P a g e
}

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;

57 | P a g e
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++)

58 | P a g e
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);

}}

59 | P a g e
60 | P a g e

You might also like