CP7111 Advanced Data Structures Lab Record
Implementation of Graph Search Algorithm
Ex.No:1 Breadth First Search and Depth First Search
Aim:
To write a java program for the implementation of graph search algorithm using the concept Breadth First Search and Depth First Search.
Algorithm:
Step1: Start the program.Step2: Enter the number of vertices and edges. Step3: Give the edge information.Step4: Push the root node in the Stack or Queue. Step5: Loop until the Stack or queue is empty. Step6: Remove the node from the stack or Queue. Step7: Then find the path from source to destination. Step8: Stop the program.
Source Code:
import java.io.*; class Node{
int data; Node link;
}class QueueBFS{
Node front,rear; QueueBFS(){
front=rear=null;}void insert(int x){
Node newrec=new Node(); newrec.data=x; newrec.link=null; if(front==null){
front=newrec;}else
P a g e 1 | 54
CP7111 Advanced Data Structures Lab Record
{rear.link=newrec;
}rear=newrec;
}int delete(){
if(front!=null){
int temp; temp=front.data; front=front.link; return temp;
}else{
System.out.println("Empty queuebfs"); return -1;
} }} class Graph{
int g[][]; int v,e;int visited[]; int a,b;QueueBFS q=new QueueBFS();void createGraph()throws IOException{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter the number of vertices:"); v=Integer.parseInt(br.readLine());System.out.println("Enter the number of edges:"); e=Integer.parseInt(br.readLine());g=new int[v+1][v+1];
for(int i=1;i<=e;i++){
System.out.println("Enter the Edge information:"); System.out.println("From="); a=Integer.parseInt(br.readLine()); System.out.println("To="); b=Integer.parseInt(br.readLine()); g[a][b]=g[b][a]=1;
}}
P a g e 2 | 54
CP7111 Advanced Data Structures Lab Record
void callBfs(){
visited=new int[v+1]; bfs(1);
}void bfs(int k){
q.insert(k);while(q.front!=null){ k=q.delete();
visited[k]=1;System.out.print(k+"\t"); for(int i=1;i<=v;i++){
if(g[k][i]!=0 && visited[i]!=1){
q.insert(i); visited[i]=1;
}} } }
}class Graph1{
int g[][]; int v,e;int visited[];void createGraph1()throws IOException{
int a,b;BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.print("\n Enter Number Of Vertices = "); v=Integer.parseInt(br.readLine());System.out.print("\n Enter Number Of Edges = "); e=Integer.parseInt(br.readLine());g=new int[v+1][v+1]; for(int i=1;i<=e;i++){
System.out.print("\n Enter Edge Infomation "); System.out.print("\n From ="); a=Integer.parseInt(br.readLine()); System.out.print("\n To ="); b=Integer.parseInt(br.readLine()); g[a][b]=g[b][a]=1;
} }
P a g e 3 | 54
CP7111 Advanced Data Structures Lab Record
void callDFS(){
visited = new int[v+1]; dfs(1);
}void dfs(int k){
System.out.print(k + "\t"); visited[k]=1;for(int i=1;i<=v;i++){
if(g[k][i] !=0 && visited[i]!=1) dfs(i);
} }}
class Graphsearch{
public static void main(String args[])throws IOException{ BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int c;
boolean i=true; while(i) {
System.out.println("\n\n MAIN MENU"); System.out.println("\n 1.BFS \t 2.DFS \t 3.EXIT"); System.out.println("\n Enter ur Choice:"); c=Integer.parseInt(br.readLine()); switch(c) {
case 1: Graph g=new Graph(); g.createGraph(); g.callBfs();
break; case 2:
Graph1 g1 = new Graph1(); g1.createGraph1(); g1.callDFS();
break; case 3:
i=false;break;
}}
}}
P a g e 4 | 54
CP7111 Advanced Data Structures Lab Record
OUTPUT:
P a g e 5 | 54
CP7111 Advanced Data Structures Lab Record
RESULT:
Thus the java program for the implementation of graph search algorithm using the concept Breadth First and Depth First search has been executed successfully.
P a g e 6 | 54
CP7111 Advanced Data Structures Lab Record
Ex.No:2 Prim’s Algorithm
Aim:
To write a java program for the implementation of graph search algorithm using the conceptPrim’s Algorithm.
Algorithm:
Step1: Start the programStep2: Enter the number of vertices and edges .Step3: Give the edge information.Step4: Enter the weight for each edge.Step5: Then calculate minimum cost.Step6: Find the Minimum Spanning Tree.Step7: Stop the program.
Source Code:
import java.io.*; import java.util.*;
class Graph{
int weight[][]=new int[20][20]; int visited[]=new int [20];int d[]=new int[20]; int p[]=new int[20]; int v,e;void creategraph()throws IOException{
int i,j,a,b,w;BufferedReader in=new BufferedReader( new InputStreamReader(System.in)); System.out.print("\nEnter number of vertices :"); v=Integer.parseInt(in.readLine());System.out.print("\nEnter number of Edges :"); e=Integer.parseInt(in.readLine());for ( i=1;i<=v;i++)
for( j=1;j<=v;j++)weight[i][j]=0;
for (i=1;i<=v;i++){
p[i]=visited[i]=0;d[i]=32767;
}
P a g e 7 | 54
CP7111 Advanced Data Structures Lab Record
for ( i=1;i<=e;i++){
System.out.print("\nEnter edge a,b and weight w :"); a=Integer.parseInt(in.readLine()); b=Integer.parseInt(in.readLine()); w=Integer.parseInt(in.readLine()); weight[a][b]=weight[b][a]=w;
}
}
void algo ()throws IOException{
creategraph();int current,total,mincost,i; current=1;d[current]=0; total=1; visited[current]=1; while(total!=v){
for (i=1;i<=v;i++){
if(weight[current][i]!=0)if(visited[i]==0)if(d[i]>weight[current][i]){
d[i]=weight[current][i];p[i]=current;
}}mincost=32767; for (i=1;i<=v;i++){
if(visited[i]==0)if(d[i]<mincost) {
mincost=d[i];current=i;
}}visited[current]=1;total++;
}mincost=0;for(i=1;i<=v;i++)mincost=mincost+d[i];
P a g e 8 | 54
CP7111 Advanced Data Structures Lab Record
System.out.print("\n Minimum cost="+mincost);System.out.print("\n Minimum Spanning tree is");
for(i=1;i<=v;i++)System.out.print("\n vertex" +i+"is connected to"+p[i]);
}}class prims{
public static void main(String args[])throws IOException{
Graph g=new Graph(); g.algo();
}}
P a g e 9 | 54
CP7111 Advanced Data Structures Lab Record
OUTPUT:
RESULT:
Thus the java program for the implementation of graph search algorithm using the concept prim’s algorithm has been executed successfully.
P a g e 10 | 54
CP7111 Advanced Data Structures Lab Record
Ex.No:3 Kruskal’s Algorithm
Aim:
To write a java program for the implementation of graph search algorithm using the conceptKruskal’s Algorithm.
Algorithm:
Step1: Start the program.Step2: Enter the number of nodes in the undirected weighted graph. Step3: Give weight for each edge.Step4: Find the minimum spanning tree, which node forms a cycle it is removed. Step5: Then find the cost for spanning tree.Step6: Stop the program.
Source Code:
import java.io.*; import java.util.*; class Graphs{int i,n; int noe;int graph_edge[][]=new int[100][4]; int tree[][]=new int [10][10];int sets[][]=new int[100][10]; int top[]=new int[100];int cost=0;
int getNumber(){String str; int ne=0;InputStreamReader input=new InputStreamReader(System.in); BufferedReader in=new BufferedReader(input);try{str=in.readLine();ne=Integer.parseInt(str);}catch(Exception e){System.out.println("I/O Error");}return ne;
P a g e 11 | 54
CP7111 Advanced Data Structures Lab Record
}
void read_graph(){System.out.print("Enter the no. of nodes in the undirected weighted graph ::"); n=getNumber();
noe=0;
System.out.println("Enter the weights for the following edges ::\n"); for(int i=1;i<=n;i++){
for(int j=i+1;j<=n;j++){
System.out.print(" < "+i+" , "+j+" > ::"); int w;w=getNumber();if(w!=0){
noe++; graph_edge[noe][1]=i; graph_edge[noe][2]=j; graph_edge[noe][3]=w;
}}
}}
void sort_edges(){
for(int i=1;i<=noe-1;i++){
for(int j=1;j<=noe-i;j++){
if(graph_edge[j][3]>graph_edge[j+1][3]){
int t=graph_edge[j][1]; graph_edge[j][1]=graph_edge[j+1][1]; graph_edge[j+1][1]=t; t=graph_edge[j][2]; graph_edge[j][2]=graph_edge[j+1][2]; graph_edge[j+1][2]=t; t=graph_edge[j][3]; graph_edge[j][3]=graph_edge[j+1][3]; graph_edge[j+1][3]=t;
P a g e 12 | 54
CP7111 Advanced Data Structures Lab Record
}}
}}void algorithm(){for(int i=1;i<=n;i++){
sets[i][1]=i;top[i]=1;
}System.out.println("\nThe algorithm starts ::\n\n"); for(i=1;i<=noe;i++){
int p1=find_node(graph_edge[i][1]); int p2=find_node(graph_edge[i][2]); if(p1!=p2){
System.out.print("The edge included in the tree is ::"); System.out.print("< "+graph_edge[i][1]+" , "); System.out.println(graph_edge[i][2]+" > ");; cost=cost+graph_edge[i][3]; tree[graph_edge[i][1]][graph_edge[i][2]]=graph_edge[i][3]; tree[graph_edge[i][2]][graph_edge[i][1]]=graph_edge[i][3]; for(int j=1;j<=top[p2];j++){
top[p1]++;sets[p1][top[p1]]=sets[p2][j];
}top[p2]=0;
}else{
System.out.println("Inclusion of the edge "); System.out.print(" < "+graph_edge[i][1]+" , ");System.out.println(graph_edge[i][2]+"> forms a cycle so it is removed\n\
n"); } }
System.out.println("Cost of the spanning tree : "+cost);}int find_node(int n){for(int i=1;i<=noe;i++){
for(int j=1;j<=top[i];j++){
P a g e 13 | 54
CP7111 Advanced Data Structures Lab Record
if(n==sets[i][j]) return i;
}}return -1;}}class Kruskal1{public static void main(String args[]){Graphs obj=new Graphs(); obj.read_graph(); obj.sort_edges(); obj.algorithm();}}
P a g e 14 | 54
CP7111 Advanced Data Structures Lab Record
OUTPUT:
RESULT:
Thus the java program for the implementation of graph search algorithm using the concept kruskal’s algorithm has been executed successfully.
P a g e 15 | 54
CP7111 Advanced Data Structures Lab Record
Implementation and application of Network flow and linear programming problems
Ex.No:4 Implementation of Maximum Flow and Minimum Cut
Aim:
To write a java program for the implementation of Network Flow by finding the maximum flow and minimum cut of a network.
Algorithm:
Step1: Start the program.Step2: Enter the number of nodes.Step3: Determine the Graph matrix.Step4: Enter the source and sink in the graph.Step5: Find the Maximum flow and minimum Cut set in the graph.Step6: Stop the program.
Source Code:
import java.util.ArrayList; import java.util.HashSet;import java.util.Iterator; import java.util.LinkedList; import java.util.Queue; import java.util.Scanner;import java.util.Set; public class NetworkFlowProb{
private int[] parent;private Queue<Integer> queue; private int numberOfVertices; private boolean[] visited; private Set<Pair> cutSet;private ArrayList<Integer> reachable; private ArrayList<Integer> unreachable;public NetworkFlowProb (int numberOfVertices){
this.numberOfVertices = numberOfVertices; this.queue = new LinkedList<Integer>(); parent = new int[numberOfVertices + 1]; visited = new boolean[numberOfVertices + 1]; cutSet = new HashSet<Pair>();reachable = new ArrayList<Integer>(); unreachable = new ArrayList<Integer>();
P a g e 16 | 54
CP7111 Advanced Data Structures Lab Record
}public boolean bfs (int source, int goal, int graph[][]){
boolean pathFound = false; int destination, element;for (int vertex = 1; vertex <= numberOfVertices; vertex++){
parent[vertex] = -1; visited[vertex] = false;
}queue.add(source); parent[source] = -1; visited[source] = true; while (!queue.isEmpty()){
element = queue.remove(); destination = 1;while (destination <= numberOfVertices){
if (graph[element][destination] > 0 && !visited[destination]){
parent[destination] = element; queue.add(destination); visited[destination] = true;
}destination++;
} } if (visited[goal]){
pathFound = true;}return pathFound;
}public int networkFlow (int graph[][], int source, int destination){
int u, v;int maxFlow = 0; int pathFlow;int[][] residualGraph = new int[numberOfVertices + 1][numberOfVertices + 1]; for (int sourceVertex = 1; sourceVertex <= numberOfVertices; sourceVertex++){
for (int destinationVertex = 1; destinationVertex <= numberOfVertices; destinationVertex++)
{residualGraph[sourceVertex][destinationVertex]
= graph[sourceVertex][destinationVertex];
P a g e 17 | 54
CP7111 Advanced Data Structures Lab Record
} }/*max flow*/while (bfs(source, destination, residualGraph)){
pathFlow = Integer.MAX_VALUE;for (v = destination; v != source; v = parent[v]){
u = parent[v];pathFlow = Math.min(pathFlow, residualGraph[u][v]);
}for (v = destination; v != source; v = parent[v]){
u = parent[v]; residualGraph[u][v] -= pathFlow; residualGraph[v][u] += pathFlow;
} maxFlow += pathFlow; }/*calculate the cut set*/for (int vertex = 1; vertex <= numberOfVertices; vertex++){
if (bfs(source, vertex, residualGraph)){
reachable.add(vertex);}else{
unreachable.add(vertex);} }
for (int i = 0; i < reachable.size(); i++){
for (int j = 0; j < unreachable.size(); j++){
if (graph[reachable.get(i)][unreachable.get(j)] > 0){
cutSet.add (new Pair(reachable.get(i), unreachable.get(j)));}} }
return maxFlow;}
public void printCutSet (){
Iterator<Pair> iterator = cutSet.iterator(); while (iterator.hasNext()){
Pair pair = iterator.next(); System.out.println(pair.source + "-" + pair.destination);
P a g e 18 | 54
CP7111 Advanced Data Structures Lab Record
} }
public static void main (String...arg){
int[][] graph;int numberOfNodes; int source;int sink;int maxFlow;Scanner scanner = new Scanner(System.in); System.out.println("Enter the number of nodes");numberOfNodes = scanner.nextInt();graph = new int[numberOfNodes + 1][numberOfNodes + 1]; System.out.println("Enter the graph matrix");for (int sourceVertex = 1; sourceVertex <= numberOfNodes; sourceVertex++){
for (int destinationVertex = 1; destinationVertex <= numberOfNodes; destinationVertex++) {
graph[sourceVertex][destinationVertex] = scanner.nextInt();} }
System.out.println("Enter the source of the graph"); source= scanner.nextInt(); System.out.println("Enter the sink of the graph"); sink = scanner.nextInt();NetworkFlowProb networkFlowProb = new NetworkFlowProb(numberOfNodes); maxFlow = networkFlowProb.networkFlow(graph, source, sink); System.out.println("The Max flow in the graph is " + maxFlow); System.out.println("The Minimum Cut Set in the Graph is "); networkFlowProb.printCutSet();scanner.close();
}}class Pair{
public int source; public int destination;public Pair(int source, int destination){
this.source = source; this.destination = destination;
}public Pair(){}}
P a g e 19 | 54
CP7111 Advanced Data Structures Lab Record
OUTPUT:
RESULT:
Thus the java program for the implementation of Network Flow by finding the maximum flow and minimum cut of a network has been successfully executed.
P a g e 20 | 54
CP7111 Advanced Data Structures Lab Record
Implementation of Algorithm using Hill Climbing and Dynamic Programming Design Technique
Ex.No:5 Travelling Salesman Problem
Aim:
To write a java program for the Implementation of hill climbing using travelling salesman problem.
Algorithm:
Step1: Start the programStep2: Enter the number of nodes.Step3: Specify the weight for each edge.Step4: Assume the starting node.Step5: Find the tour and its cost.Step6: Stop the program.
Source Code:
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();
P a g e 21 | 54
CP7111 Advanced Data Structures Lab Record
}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;minindex=inputSet[i];
}}return minindex; }public void eval(){
P a g e 22 | 54
CP7111 Advanced Data Structures Lab Record
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)+"-"); 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();}
}
P a g e 23 | 54
CP7111 Advanced Data Structures Lab Record
OUTPUT:
RESULT:
Thus the java program for the implementation of Hill climbing algorithm using travelling salesman problem has been executed successfully.
P a g e 24 | 54
CP7111 Advanced Data Structures Lab Record
Ex.No:6 Longest Common Subsequences
Aim:
To write a java program for the Implementation of dynamic programming using longest common subsequences problem.
Algorithm:
Step1: Start the program.Step2: Enter the string1 and string2.Step3: Determine the common sequence by matching the strings.Step4: Find the length of longest common subsequence.Step5: Display the common sequence between the given input strings.Step6: Stop the program.
Source Code:
import java.util.*; class lcs{
static class cell{
int cost, parent;}static final int MAXLEN = 100;static cell m[][] = new cell[MAXLEN][MAXLEN]; static final int MATCH = 0;static final int INSERT = 1; static final int DELETE = 2; static int indel(char c){return 1;}static int match(char c, char d){
if(c==d) return 0; return MAXLEN;
}static void row_init(int i){
m[0][i].cost = i;if (i>0) m[0][i].parent = INSERT; else m[0][i].parent = -1; }
static void column_init(int i){
m[i][0].cost = i;
P a g e 25 | 54
CP7111 Advanced Data Structures Lab Record
if (i>0) m[i][0].parent = DELETE; else m[0][i].parent = -1;
}static int string_compare(String s, String t){
for(int i=0;i<MAXLEN;i++){
row_init(i); column_init(i);
} int k, lowest_cost;int opt[] = new int [3]; for(int i=1;i<s.length();i++)
for(int j=1;j<t.length();j++){
opt[MATCH] = m[i-1][j-1].cost + match(s.charAt(i),t.charAt(j)); opt[INSERT] = m[i][j-1].cost + indel(t.charAt(j)); opt[DELETE] = m[i-1][j].cost + indel(s.charAt(i));m[i][j].cost = opt[MATCH]; m[i][j].parent = MATCH;for (k=INSERT; k<=DELETE; k++)
if (opt[k] < m[i][j].cost){
m[i][j].cost = opt[k]; m[i][j].parent = k;
}}return m[s.length()-1][t.length()-1].cost;
}static void print_matrix(String s, String t, boolean costQ){
int x = s.length(); int y = t.length();System.out.printf(" "); for(int i=0;i<y;i++)System.out.printf(" %c",t.charAt(i)); System.out.printf("\n");for(int i=0; i<x; i++) { System.out.printf("%c: ",s.charAt(i)); for(int j=0; j<y; j++) {if(costQ)System.out.printf(" %2d",m[i][j].cost); else
System.out.printf(" %2d",m[i][j].parent);}System.out.printf("\n");
}}static void reconstruct_path(String s, String t, int i, int j)
P a g e 26 | 54
CP7111 Advanced Data Structures Lab Record
{if(m[i][j].parent == -1) return; if (m[i][j].parent == MATCH) {
reconstruct_path(s,t,i-1,j-1); match_out(s, t, i, j);return;
}if (m[i][j].parent == INSERT)
{ reconstruct_path(s,t,i,j-1);insert_out(t,j); return;
}if (m[i][j].parent == DELETE)
{ reconstruct_path(s,t,i-1,j); delete_out(s,i);return;
}return;}static void match_out(String s, String t, int i, int j){
if(s.charAt(i) == t.charAt(j)) System.out.printf("%c",s.charAt(i));}static void insert_out(String t, int j) {}static void delete_out(String s, int i) {}static public void main(String[] args){
for(int i=0;i<MAXLEN;i++)for(int j=0;j<MAXLEN;j++)
m[i][j]=new cell();String s = new String(); String t = new String();Scanner sc = new Scanner(System.in); System.out.println("Enter the String1:"); s=sc.next();System.out.println("Enter the String2:"); t=sc.next();s=" " + s; t=" " + t;int complen = string_compare(s,t);int lcslen = (s.length() + t.length() - 2 - complen) / 2; System.out.printf("length of longest common subsequence = %d\n", lcslen); System.out.printf("Common Sequence:",complen); reconstruct_path(s,t,s.length()-1,t.length()-1);
}}
P a g e 27 | 54
CP7111 Advanced Data Structures Lab Record
OUTPUT:
RESULT:
Thus the java program for the implementation of Dynamic Programming using longest common subsequences problem has been executed successfully.
P a g e 28 | 54
CP7111 Advanced Data Structures Lab Record
Implementation of Recursive Backtracking Algorithms
Ex.No:7 N Queens Problem
Aim:
To write a java program for implementation of Recursive Backtracking Algorithms using N Queens Problem.
Algorithm:
Step1: Start the program. Step2: Enter the board size.Step3: Then place the queen based on board size. Step4: Find the solution for given board size.Step5: Check the condition board size less than or equal to row and column the print ‘Q’. Step6: Otherwise print dot(.). Step7: Repeat Step5 until there is no solution possible. Step8: Stop the program.
Source Code:
import java.util.Scanner; public class Queens{
protected int boardSize; protected boolean[][] board; public Queens (int boardSize){
this.boardSize = boardSize;board = new boolean[boardSize][boardSize]; for (int row = 0; row < boardSize; row++)
for (int column = 0; column < boardSize; column++) board[row][column] = false;
}protected boolean placeQueen (int column){
int row;if (column == boardSize){
return true;}else{
boolean successful = false; row = 0;
P a g e 29 | 54
CP7111 Advanced Data Structures Lab Record
while ((row < boardSize) && !successful){
if (threat (row, column)){
row++;}else{
board[row][column] = true;successful = placeQueen (column + 1); if (!successful){
board[row][column] = false; row++;
}}}return successful;
} } protected boolean threat (int row, int column)
{for (int c = 0; c < column; c++){
if (board[row][c]){
return true;} }
for (int c = 1; c <= column; c++){
if (row < c){
break;}
if (board[row - c][column - c]){
return true;} }
for (int c = 1; c <= column; c++){
if (row + c >= boardSize){
break;}
if (board[row + c][column - c]){
return true;
P a g e 30 | 54
CP7111 Advanced Data Structures Lab Record
} }return false;
}protected void outputBoard(){
System.out.println("Solution for board of size " + boardSize + ":"); for (int row = 0; row < boardSize; row++){
for (int column = 0; column < boardSize; column++){
if (board[row][column]){
System.out.print("Q ");}else{
System.out.print(". ");}}
System.out.println();}
System.out.println();}public void solve(){
if (placeQueen(0)){
outputBoard();}else{
System.out.println("There is no solution possible");} }
public static void main (String[] args){
Queens board;Scanner input = new Scanner (System.in);System.out.print("Enter the board Size: "); //Gain Size of board from user int boardSize = input.nextInt();input.close();board = new Queens(boardSize); board.solve();
}}
P a g e 31 | 54
CP7111 Advanced Data Structures Lab Record
OUTPUT:
RESULT:
Thus the java program for the implementation of recursive backtracking algorithm using NQueens problem has been executed successfully.
P a g e 32 | 54
CP7111 Advanced Data Structures Lab Record
Ex.No:8 Permutations
Aim:
To write a java program for implementation of Recursive Backtracking Algorithms using Permutation Problem.
Algorithm:
Step1: Start the program. Step2: Enter the initial string.Step3: Find the permutation for given string.Step4: Check the condition for ending string which is less than or equal to value 1. Step5: Print the string.Step6: Stop the program.
Source Code:
import java.io.*; public class permutation{
public static void main(String args[]) throws IOException{
String str;System.out.println("Enter the initial string");BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); str=br.readLine();System.out.println("Permutations are :"); permute("", str);
}public static void permute(String beginningString, String endingString){
if (endingString.length() <= 1) System.out.println(beginningString + endingString);
elsefor (int i = 0; i < endingString.length(); i++){
try {String newString = endingString.substring(0, i) + endingString.substring(i + 1); permute(beginningString + endingString.charAt(i), newString);
} catch (StringIndexOutOfBoundsException exception){
exception.printStackTrace() } }}}
P a g e 33 | 54
CP7111 Advanced Data Structures Lab Record
OUTPUT:
RESULT:
Thus the java program for the implementation of recursive backtracking algorithm using Permutation problem has been executed successfully.
P a g e 34 | 54
CP7111 Advanced Data Structures Lab Record
Implementation of Randomized Algorithms
Ex.No:9 Quick Sort
Aim:
To write a java program for the implementation of Randomized Algorithms using Quick Sort problem.
Algorithm:
Step1: Start the program.Step2: Enter the limit for its elements.Step3: Check if low is less than or equal to high then, temp=a[low];
a[low]=a[high]; a[high]=temp;Step4: Then increment low and decrement high.Step5: Display the sorted array elements in ascending order. Step6: Stop the program.
Source Code:
import java.io.*; import java.util.Scanner;import java.util.Random; public class quicksort{
private static final Random rnd =new Random(); public static void main(String[] args){
int i;Scanner in=new Scanner(System.in); System.out.println(" Quick Sort\n");System.out.println("Enter the no. of elements in the array:\n"); int arr_val=in.nextInt();int array[]=new int[arr_val]; try{
BufferedReaderbr=new BufferedReader(new InputStreamReader(System.in)); System.out.println("\nEnter the Array Elements:\n");for(i=0;i<arr_val;i++){
array[i]=Integer.parseInt(br.readLine());}
}catch(Exception ex){}
P a g e 35 | 54
CP7111 Advanced Data Structures Lab Record
System.out.println("\nValues Before the sort:\n"); for(i = 0; i < array.length; i++)System.out.print( array[i]+" "); System.out.println("\n"); System.out.println("Pivot Values\n"); quickSort(array,0,array.length-1); System.out.print("\nValues after the sort:\n"); for(i = 0; i <array.length; i++){
System.out.print(array[i]+" ");}System.out.println("\n");
}public static int partition(int arr[], int left, int right)
{ int i = left, j = right;int tmp;int pivot = arr[left + rnd.nextInt(right - left)]; System.out.println(+pivot);while (i <= j) { while (arr[i] < pivot)i++;
while (arr[j] > pivot)j--;
if (i <= j) { tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; i++;
j--;}
}; return i;
}
public static void quickSort(int arr[], int left, int right) { int index = partition(arr, left, right);
if (left < index - 1) quickSort(arr, left, index - 1); if (index < right)
quickSort(arr, index, right);}
}
OUTPUT:
P a g e 36 | 54
CP7111 Advanced Data Structures Lab Record
RESULT:
Thus the java program for the implementation of randomized algorithm using quick sort problem has been executed successfully.
P a g e 37 | 54
CP7111 Advanced Data Structures Lab Record
Ex.No:10 Matrix Multiplication
Aim:
To write a java program for the implementation of Randomized Algorithms using Matrix Multiplication problem.
Algorithm:
Step1: Start the program.Step2: Enter the matrix dimension. Step3: Then create a matrices function.Step4: Fill the first matrix with the random numbers.Step5: Check the condition for the first matrix that number less than dimension. Step6: Then fill the second matrix with the random numbers.Step7: Check the condition for the second matrix that number less than dimension. Step8: Multiplying the matrices. Step9: Display the resulting matrix. Step10: Stop the program.
Source Code:
import java.util.Scanner; import java.util.Random;
public class Matrix{
public static void main(String[]args){
Scanner keyboard = new Scanner(System.in); System.out.printf("Type in the matrix dimension.\n"); int dimension = keyboard.nextInt();int matrix1[][] = new int[dimension][dimension]; int matrix2[][] = new int[dimension][dimension]; int result[][] = new int[dimension][dimension]; for (int i = 0; i < dimension; i++){
for (int j = 0; j < dimension; j++){ Random rand = new Random(); int r = rand.nextInt(9);matrix1 [i][j] = r;
}}
System.out.printf("\nMatrix One:\n");
P a g e 38 | 54
CP7111 Advanced Data Structures Lab Record
for (int i = 0; i < dimension; i ++){ System.out.printf("\n");for (int j = 0; j < dimension; j++)
{ System.out.printf("%d ", matrix1[i][j]); System.out.printf("\t");
}}
for (int i = 0; i < dimension; i++){for (int j = 0; j < dimension; j++)
{ Random rand1 = new Random(); int r1 = rand1.nextInt(9); matrix2 [i][j] = r1;
}}
System.out.printf("\n\nMatrix Two:\n"); for (int i = 0; i < dimension; i ++){
System.out.printf("\n");for (int j = 0; j < dimension; j++)
{ System.out.printf("%d ", matrix2[i][j]); System.out.printf("\t");
}}
for (int i = 0; i < matrix1.length;i++){for (int j = 0; j < matrix2.length; j++){
for (int k = 0; k < matrix2.length; k++){ result[i][j] += matrix1[i][k] * matrix2[k][j];
}}
} System.out.printf("\n\nMultiplied Matrix:\n");
for (int i = 0; i < dimension; i++){ System.out.printf("\n");for (int j = 0; j < dimension; j++)
{ System.out.printf("%d ", result[i][j]); System.out.printf("\t");
}}System.out.printf("\n");
}}
P a g e 39 | 54
CP7111 Advanced Data Structures Lab Record
OUTPUT:
RESULT:
Thus the java program for the implementation of randomized algorithm using matrix multiplication problem has been executed successfully.
P a g e 40 | 54
CP7111 Advanced Data Structures Lab Record
Implementation of various Locking and Synchronization Mechanisms for Concurrent Linked Lists, Concurrent Queues, and Concurrent Stacks.
Ex.No : 11 Concurrent Linked List
Aim:
To write a java program to implement the various locking and synchronization mechanisms for Concurrent Linked List.
Algorithm:
Step 1: Start the program.Step 2: Include the necessary packages. Step 3: Define the Linked Node definition.Step 4: Create a constructor to build a node with null and specified constructor. Step 5: Create a linked list class. Step 6: Check for assertion if the assertion is not true then it throws java.lang.assertion error. Step 7: Create a function to check if the list is empty or not.Step 8: Display the result. Step 9: Stop the program.
Source Code:
import java.util.Collections; import java.util.LinkedList; import java.util.List;
public class EarlyNotify extends Object { private List list; public EarlyNotify() {list = Collections.synchronizedList(new LinkedList());
}
public String removeItem() throws
InterruptedException { synchronized (list) {while (list.isEmpty()) { print("wait()"); list.wait();print("done with wait()");
}String item = (String) list.remove(0);
P a g e 41 | 54
CP7111 Advanced Data Structures Lab Record
return item;}
}
public void addItem(String item) { print("entering");synchronized (list) { list.add(item);print("added: '" + item + "'");
list.notifyAll();print("notified");
}print("leaving");
}
private static void print(String msg) {String name = Thread.currentThread().getName(); System.out.println(name + ": " + msg);
}
public static void main(String[] args) { final EarlyNotify enf = new EarlyNotify();
Runnable runA = new Runnable() { public void run() {try {
String item = enf.removeItem(); print("returned: '" + item + "'");
} catch (InterruptedException ix) { print("interrupted!");
} catch (Exception x) { print("threw an Exception!!!\n" + x);
}}
};
Runnable runB = new Runnable() { public void run() {enf.addItem("Hello!");
}};
try {Thread threadA1 = new Thread(runA, "A");
P a g e 42 | 54
CP7111 Advanced Data Structures Lab Record
threadA1.start();
Thread.sleep(500);
Thread threadA2 = new Thread(runA, "B"); threadA2.start();
Thread.sleep(500);
Thread threadB = new Thread(runB, "C"); threadB.start();
Thread.sleep(1000);
threadA1.interrupt();threadA2.interrupt();
} catch (InterruptedException x) {}
}}
P a g e 43 | 54
CP7111 Advanced Data Structures Lab Record
OUTPUT :
RESULT :
Thus a java program to implement the various locking and synchronization mechanisms for Concurrent Linked List has been executed successfully.
P a g e 44 | 54
CP7111 Advanced Data Structures Lab Record
Ex.No : 12 Concurrent Queue
Aim:
To write a java program to implement producer consumer problem using concurrent blocking Queue.
Algorithm:
Step 1: Start the program.Step 2: Include the necessary packages.Step 3: Create the shared object for the class using blocking queue.Step 4: Create producer class in java.Step 5: Create consumer class in java.Step 6: Display the result.Step 7: Stop the program.
Source Code:
import java.io.*; import java.util.concurrent.BlockingQueue;import java.util.concurrent.LinkedBlockingQueue; import java.util.logging.Level;import java.util.logging.Logger; public class ProducerConsumerPattern{
public static void main(String args[]){
BlockingQueue sharedQueue = new LinkedBlockingQueue(); Thread prodThread = new Thread(new Producer(sharedQueue)); Thread consThread = new Thread(new Consumer(sharedQueue)); prodThread.start();consThread.start();
}}
class Producer implements Runnable{
private final BlockingQueue sharedQueue; public Producer(BlockingQueue sharedQueue){this.sharedQueue = sharedQueue;}public void run(){for(int i=0; i<10; i++)
P a g e 45 | 54
CP7111 Advanced Data Structures Lab Record
{try {
System.out.println("Produced: " + i); sharedQueue.put(i);
}catch (InterruptedException ex){
Logger.getLogger(Producer.class.getName()).log(Level.SEVERE, null, ex);}
}}
}
class Consumer implements Runnable{
private final BlockingQueue sharedQueue; Consumer (BlockingQueue sharedQueue){ this.sharedQueue = sharedQueue;
}public void run(){while(true){
try{System.out.println("Consumed: "+ sharedQueue.take());}catch (InterruptedException ex){Logger.getLogger(Consumer.class.getName()).log(Level.SEVERE, null, ex);}
}}
}
P a g e 46 | 54
CP7111 Advanced Data Structures Lab Record
OUTPUT :
RESULT :
Thus a java program to implement producer consumer problem using concurrent blocking Queue has been successfully executed.
P a g e 47 | 54
CP7111 Advanced Data Structures Lab Record
Ex.No : 13 Concurrent Stack
Aim:
To write a java program to implement concurrent stack using push and pop.
Algorithm:
Step 1: Start the program.Step 2: Include the necessary packages.Step 3: Create a class stackimpl2Step 4: Initialize the stack using push and pop.Step 5: Create a wait() method that is called to pop the waiting element.Step 6: Create a notify() method to notify the popped elements.Step 7: Stackuser class has been created to extends thread.Step 8: Start Daemon thread using set daemon.Step 9: Start this thread.Step10: Display the result.
Source Code:
Import java.io.*; class StackImpl2{
private Object[] stackArray; private volatile int topOfStack; StackImpl2 (int capacity){
stackArray = new Object[capacity]; topOfStack = -1;
}public synchronized Object pop(){
System.out.println(Thread.currentThread() + ": popping"); while (isEmpty())try{
System.out.println(Thread.currentThread() + ": waiting to pop"); wait(); // (1)
}catch (InterruptedException e) { }Object obj = stackArray[topOfStack]; stackArray[topOfStack--] = null;System.out.println(Thread.currentThread() + ": notifying after pop");
P a g e 48 | 54
CP7111 Advanced Data Structures Lab Record
P a g e 49 | 54
}}class StackPopper extends StackUser { // (9) Popper
StackPopper(String threadName, StackImpl2 stack){
super(threadName, stack);}public void run()
// (7) Daemon thread // (8) Start this thread
super(threadName); this.stack = stack; System.out.println(this); setDaemon(true); start();
notify(); return obj;
// (2)
}public synchronized void push(Object element){
System.out.println(Thread.currentThread() + ": pushing"); while (isFull())try{
System.out.println(Thread.currentThread() + ": waiting to push"); wait(); // (3)
}catch (InterruptedException e) { }stackArray[++topOfStack] = element; System.out.println(Thread.currentThread() + ": notifying after push"); notify(); // (4)
} public boolean isFull(){
return topOfStack >= stackArray.length -1;}
public boolean isEmpty(){
return topOfStack < 0;}
}abstract class StackUser extends Thread{ // (5) Stack user protected StackImpl2 stack; // (6) StackUser(String threadName, StackImpl2 stack)
{
CP7111 Advanced Data Structures Lab Record
{while (true) stack.pop();
}}class StackPusher extends StackUser{ // (10) Pusher
StackPusher(String threadName, StackImpl2 stack){
super(threadName, stack);}public void run(){
while (true) stack.push(new Integer(1));}
}public class WaitAndNotifyClient{
public static void main(String[] args)throws InterruptedException{ // (11)
StackImpl2 stack = new StackImpl2(5); new StackPusher("A", stack);new StackPusher("B", stack); new StackPopper("C", stack);System.out.println("Main Thread sleeping."); Thread.sleep(10);System.out.println("Exit from Main Thread.");
}}
P a g e 50 | 54
CP7111 Advanced Data Structures Lab Record
OUTPUT :
RESULT :
Thus to write a java program to implement concurrent stack using push and pop has been executed successfully.
P a g e 51 | 54
CP7111 Advanced Data Structures Lab Record
Developing applications involving concurrency.
Ex.No : 14 Sleeping Barber Problem
Aim:To write a java program to implement Sleeping Barber problem using Concurrency.
Algorithm:
Step 1: Import the header files.Step 2: Declare the number of chairs and barbers in the shop Step 3: Enter the number of customer.Step 4: If there is no customer to be served, the barber goes to sleep.Step 5:If a customer enters the barber shop whole chairs are occupied, then the customer
leaves the Shop. Step 6: If the barber is busy, but chairs are available in waiting room then the customer
sits in one of the free chairs until the barber is idle.Step 7: Barber class which extends threads is used to simulate multiple sleeping barbers
Source Code:
import java.io.*; import java.lang.*; class cust{
public int disp(int cn){
return(cn);}
}class em1 extends
Thread{ Barber m=new Barber(); cust c=new cust();public synchronized void run(){
try{
while(m.cnum<=m.n){
int t=c.disp(m.cnum++); System.out.println("Barber2 serves Customer "+t); Thread.sleep(2000);
}
P a g e 52 | 54
CP7111 Advanced Data Structures Lab Record
System.out.println("Barber2 sleeps ");}catch(Exception e){}
}}public class Barber{
static int cnum=1,n,ch,n1;public static void main(String[] args){ try
{BufferedReaderbr=newBufferedReader(new InputStreamReader(System.in)); em1 e=new em1();cust c=new cust(); int j;System.out.println("Enter no of Chairs including two barber Chairs: "); ch=Integer.parseInt(br.readLine()); System.out.println("Enter no of Customers : "); n=Integer.parseInt(br.readLine());
e.start();if(ch<n){
n1=n-ch;System.out.println(n1+" Customers Leaved from the Shop"); n=n-n1;while(cnum<=n){
int t=c.disp(cnum++);System.out.println("Barber1 serves " +" Customer " + t); Thread.sleep(1000);
}}else{
while(cnum<=n){
int t=c.disp(cnum++);System.out.println("Barber1 serves " +" Customer " + t); Thread.sleep(1000);
}}System.out.println("Barber1 sleeps ");
}catch(Exception e){}
}}
P a g e 53 | 54
CP7111 Advanced Data Structures Lab Record
OUTPUT :
RESULT :
Thus a java program to implement Sleeping Barber problem using Concurrency has been executed successfully.
P a g e 54 | 54