EX. No:1 Implementation of Graph Search Algorithms

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 55

EX.

No:1
EX. No:1(a )

Implementation of graph search algorithms.


DFS-BFS

Aim:
To create a depth first search to breadth first search by using the graph search
algorithms.
Algorithm:
Step 1: Push the root node in the Stack.
Step 2: Loop until stack is empty.
Step 3: Peek the node of the stack.
Step 4: If the node has unvisited child nodes, get the unvisited child node, mark it
as traversed and push it on stack.
Step 5: If the node does not have any unvisited child nodes, pop the node from the
stack.
Program:
Import java.io.*;
Import java.util.*;
Import java.util.LinkedList;
Import java.util.Queue;
Public class DFS_BFS
{
Public static void main(string[] args)
{
New DFS_BFS();//I like doing things this way so I dont have to use static objects
}
int N;//number of vertices in the graph
Boolean[][]G;//the graph as an adjacency matrix
//G[i][j]is true if there is an edge from 1
DFS_BFS()
{
setupGraph();
System.out.println(---------------);
CP7111 Advanced Data Structures Laboratory

Page 1

System.out.println();
DFS();
System.out.println();
System.out.print(-----------------);
System.out.println();
BFS();
}
Void setupGraph()
{
N=8;
G=new Boolean[N][N];
G[0][1]=G[1][0]=true;
G[0][2]=G[2][0]=true;
G[0][3]=G[3][0]=ture;
G[1][4]=G[4][1]=ture;
G[2][5]=G[5][3]=ture;
G[5][6]=G[6][5]=ture;
G[5][7]=G[7][5]=ture;
G[6][7]=G[7][6]=ture;
}
Void DFS()
{
Boolean[]V=new Boolean[N];
Int numComponets=0;
For (int i=0;i<N;i++)
If(!V[i])
{
++numComponets;
System.out.printf(Starting a DFS for component %d starting at node %d
%n,numComponets,i);
DFS(i,V)
}
System.out.println();
CP7111 Advanced Data Structures Laboratory

Page 2

System.out.printf(Finished with DFS found %d components.


%n,numComponets);
}
Void DFS(int at,Boolean[] V)
{
System.out.printf(At node %d in the DFS%n,at);
V[at]=true;
For(int i=0;i<N;i++)
If(G[at][i]&&!V[i])
{
System.out.printf(Going to node %d,i);
DFS(i,V)
}
System.out.printf(Done processing node %d%n,at);
}
Void BFS()
{
Boolean[] V=new Boolean[N];
Int numComponets=0;
For(int i=0;i<N;i++)
If(!V[i])
{
++numComponets;
System.out.printf(starting a BFS for compound %d starting at node %d
%n,numComponets,i);
BFS(i,V)
}
System.out.println();
System.out.printf(Finished with BFS found %d components.
%n,numComponets);
}
Void BFS(int start,Boolean[]V)
{
Queue<integer>Q=new LinkedList<Integer>();
Nodes
CP7111 Advanced Data Structures Laboratory

Page 3

Q.offer(start);
V[start]=ture;
While (!Q.isEmpty())
{
Int at=Q.poll();
System.out.printf(At node %d in the BFS%n,at);
For (int i=0;i<N;i++)
If(G[at][i]&&!V[i])
{
Q.offer(i);
V[i]=true;
System.out.printf(Adding node %d to the queue in the BFS%n,i);
System.out.printf(Done processing node %d%nat);
}
System.out.printf(Finished with the BFS from start node %d%n,start);
}
}

OUTPUT:
CP7111 Advanced Data Structures Laboratory

Page 4

$ javac DFS_BFS.java
$ java DFS_BFS
----------------------------Starting a DFS for component 1 starting at node 0
At node 0 in the DFS
Going to node 1.. At node 1 in the DFS
Going to node 4.. At node 4 in the DFS
Going to node 6.. At node 6 in the DFS
Done processing node 3
Done processing node 4
Done processing node 1
Going to node 2.. At node 2 in the DFS
Done processing node 2
Done processing node 0
Starting a DFS for component 2 starting at node 5
At node 5 in the DFS
Going to node 6.. At node 6 in the DFS
Going to node 7.. At node 7 in the DFS
Done processing node 7
Done processing node 6
Done processing node 5
Finished with DFS-Found 2 components
-----------------------------

Result:
Thus the java program for performing Depth first searchand breadth first search
algorithm has been executed successfully and the output is verified.
EX.No:1(b )

Dijkstras shortest path algorithm

CP7111 Advanced Data Structures Laboratory

Page 5

Aim:
To Create a Dijkstras shortest path algorithm by using the graph search
algorithms
Algorithm:
1) Create a set sptSet (shortest path tree set) that keeps track of vertices included in
shortest path tree, i.e., whose minimum distance from source is calculated and
finalized. Initially, this set is empty.
2) Assign a distance value to all vertices in the input graph. Initialize all distance
values as INFINITE. Assign distance value as 0 for the source vertex so that it is
picked first.
3) While sptSet doesnt include all vertices
.a) Pick a vertex u which is not there in sptSetand has minimum distance value.
.b) Include u to sptSet.
.c) Update distance value of all adjacent vertices of u. To update the distance
values, iterate through all adjacent vertices for every adjacent vertex v, if sum of
distance value of u (from source) and weight of edge u-v, is less than the distance
value of v, then update the distance value of v.
Program:
import java.util.HashSet;
import java.util.InputMismatchException;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;
public class Dijkstras_Shortest_Path
{
private int
distances[];
private Set<Integer> settled;
private Set<Integer> unsettled;
private int
number_of_nodes;
private int
adjacencyMatrix[][];
CP7111 Advanced Data Structures Laboratory

Page 6

public Dijkstras_Shortest_Path(int number_of_nodes)


{
this.number_of_nodes = number_of_nodes;
distances = new int[number_of_nodes + 1];
settled = new HashSet<Integer>();
unsettled = new HashSet<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++)
{
distances[i] = Integer.MAX_VALUE;
}
unsettled.add(source);
distances[source] = 0;
while (!unsettled.isEmpty())
{
evaluationNode = getNodeWithMinimumDistanceFromUnsettled();
unsettled.remove(evaluationNode);
settled.add(evaluationNode);
evaluateNeighbours(evaluationNode);
}
}
private int getNodeWithMinimumDistanceFromUnsettled()
{
int min;
CP7111 Advanced Data Structures Laboratory

Page 7

int node = 0;
Iterator<Integer> iterator = unsettled.iterator();
node = iterator.next();
min = distances[node];
for (int i = 1; i <= distances.length; i++)
{
if (unsettled.contains(i))
{
if (distances[i] <= min)
{
min = distances[i];
node = i;
}
}
}
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)
{
edgeDistance = adjacencyMatrix[evaluationNode][destinationNode];
newDistance = distances[evaluationNode] + edgeDistance;
if (newDistance < distances[destinationNode])
CP7111 Advanced Data Structures Laboratory

Page 8

{
distances[destinationNode] = newDistance;
}
unsettled.add(destinationNode);
}
}
}
}
public static void main(String... arg)
{
int adjacency_matrix[][];
int number_of_vertices;
int source = 0, destination = 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)
{
CP7111 Advanced Data Structures Laboratory

Page 9

adjacency_matrix[i][j] = Integer.MAX_VALUE;
}
}
}
System.out.println("Enter the source ");
source = scan.nextInt();
System.out.println("Enter the destination ");
destination = scan.nextInt();
Dijkstras_Shortest_Path dijkstrasAlgorithm = new
Dijkstras_Shortest_Path(
number_of_vertices);
dijkstrasAlgorithm.dijkstra_algorithm(adjacency_matrix, source);
System.out.println("The Shorted Path from " + source + " to " + destination
+ " is: ");
for (int i = 1; i <= dijkstrasAlgorithm.distances.length - 1; i++)
{
if (i == destination)
System.out.println(source + " to " + i + " is "
+ dijkstrasAlgorithm.distances[i]);
}
} catch (InputMismatchException inputMismatch)
{
System.out.println("Wrong Input Format");
}
scan.close();
}
}

Output:
CP7111 Advanced Data Structures Laboratory

Page 10

$ javac Dijkstras.java
$ java Dijkstras
Enter the number of vertices
5
Enter the Weighted Matrix for the graph
09653
00000
02040
00000
00000
Enter the source
1
Enter the destination
4
The Shorted Path from 1 to 4 is:
1 to 4 is 5

Result:
Thus the java program for performing Dijkstras_Shortest_Path algorithm has been
executed successfully and the output is verified.

CP7111 Advanced Data Structures Laboratory

Page 11

EX. No:2

EX.NO(2a)

Implementation and application of network flow and


linear programming problems.

Network Flow problems( EDMONDKARPS Algorithm)

Aim:
To Create a network flow problems using EdmondKarps algorithm.
Algorithm :
1: f 0; Gf G
2: while Gf contains an s t path P do
3: Let P be an s t path in Gf with the minimum number of edges.
4: Augment f using P.
5: Update Gf
6: end while
7: return f
Program:
importjava.io.BufferedReader;
importjava.io.InputStreamReader;
importjava.util.Arrays;
importjava.util,linkedList;
import java.util.queue;
Public class Edmondkarp{
Public static void ain(string[]args) throws Exception
{
BufferedReader br=new BufferedReader(new bufferedReader(new
inputStreamReader(System.in));
System.out.print(Enter no of vertices:);
int N= Integer.parseInt(br.readLine());
System.out.println();
int[][] neighbourLists=new int[N][];
int[][] capacityMatrix=new int[N][N];
for(int i=0;i<N;i++)
{
CP7111 Advanced Data Structures Laboratory

Page 12

System.out.print(Enter no of Edges for Vertex+(i)+:);


int E=Integer.parseInt(br.readLine());
System.out.println();
neighbourLists[i]=new int[E];
for(int j=0;j<E;++j)
{
System.out.println(Enter deatails of Edge+(j+1));
System.out.print(Enter the target node:);
int node=Integer.parseInt(br.readLine());
System.out.println();
System.out.print(Enter capacity:);
int capacity= Integer.parseInt(br.readLine());
System.out.println();
neighbourLists[i][j]=node;
capacityMatrix[i][node]=capacity;
}}
System.out.print(Enter source vertex:);
int source=Integer.parseInt(br.readLine());
System.out.println();
System.out.print(Enter Sink vertex:);
int sink=Integer.parseInt(br.readLine());
System.out.println();
System.out.println(The MAXFLOW for current input
is+edmondskarp(neighbourLists, capacityMatrix, source, sink));
}
public static int edmondskarp(int[][] E, int[][] C,int s,int t)
{
int n=C.length;
int[][] F=new int[n][n];
while(true)
{
int[]P=new int[n];
Arrays.fill(P,-1);
P[s]=s;
int[] M= new int[n];
CP7111 Advanced Data Structures Laboratory

Page 13

M[s]=Integer.MAX_VALUE;
Queue<Integer>Q= new.LinkedList<Integer>();
Q.offers(s);
LOOP:
While(!Q.isEmpty())
{
int u =Q.poll();
for(int v:E[u])
{
If(C[u][v]-F[u][v]>0&&p[v]==-1)
{
P[v]=u;
M[v] = Math.min(M[u], C[u][v]-F[u][v]);
If(v!=t)
Q.offer(v);
Else
{
While(P[v]!=v)
{
u=P[v];
F[u][v]+=M[t];
F[u][v]-=M[t];
V=u;
}
break LOOP;
}
}
}
}
if(P[t]==-1)
{
int sum=0;
for(int x:F[s])
sum +=x;
return sum;
CP7111 Advanced Data Structures Laboratory

Page 14

}
}
Output:
$ javac Edmondskarp.java
$ java Edmondskarp.java
Enter no of Vertices : 7
Enter no of Edges for vertex 0 : 2
Enter details of Edge 1
Enter target node : 1
Enter Capacity : 3
Enter details of Edge 2
Enter target node : 3
Enter Capacity : 3
Enter no of Edges for vertex 1 : 1
Enter details of Edge 1
Enter target node : 2
Enter Capacity : 4
Enter no of Edges for vertex 2 : 3
Enter details of Edge 1
Enter target node : 0
Enter Capacity : 3
Enter details of Edge 2
Enter target node : 3
Enter Capacity : 1
Enter details of Edge 3
Enter targetnode : 4
Enter Capacity : 2
Enter no of Edges for vertex 3 : 2
Enter details of Edge 1
Enter target node : 4
Enter Capacity : 2
Enter details of Edge 2
Enter target node : 5
Enter Capacity : 6
CP7111 Advanced Data Structures Laboratory

Page 15

Enter no of Edges for vertex 4 : 2


Enter details of Edge 1
Enter target node : 1
Enter Capacity : 1
Enter details of Edge 2
Enter target node : 6
Enter Capacity : 1
Enter no of Edges for vertex 5:1
Enter details of Edge 1
Enter target node : 6
Enter Capacity : 9
Enter no of Edges for vertex 6:0
Enter Source Vertex :0
Enter Sink Vertex:6
The MAX FLOW for current inputs is:4

Result:
Thus the java program for performing network flow problems using EdmondKarps
algorithm has been executed successfully and the output is verified.

EX.NO:2(b)

Linear Programming Problems

CP7111 Advanced Data Structures Laboratory

Page 16

Aim:
To Create a Linear Programming problems using java.
Algorithm :
Linear Search ( Array c, Value n)
Step 1: Set i to 1
Step 2: if i > n then go to step 7
Step 3: if c[i] = x then go to step 6
Step 4: Set i to i + 1
Step 5: Go to Step 2
Step 6: Print Element n Found at index i and go to step 8
Step 7: Print element not found
Step 8: Exit
Program:
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;
CP7111 Advanced Data Structures Laboratory

Page 17

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>();
}
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++;
}
CP7111 Advanced Data Structures Laboratory

Page 18

}
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];
}
}
/*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]);
CP7111 Advanced Data Structures Laboratory

Page 19

}
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;
}
CP7111 Advanced Data Structures Laboratory

Page 20

public void printCutSet ()


{
Iterator<Pair> iterator = cutSet.iterator();
while (iterator.hasNext())
{
Pair pair = iterator.next();
System.out.println(pair.source + "-" + pair.destination);
}
}
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");
CP7111 Advanced Data Structures Laboratory

Page 21

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

Output:
CP7111 Advanced Data Structures Laboratory

Page 22

$javac NetworkFlowProb.java
$java NetworkFlowProb
Enter the number of nodes
6
Enter the graph matrix
0 16 13 0 0 0
0 0 10 12 0 0
0 4 0 0 14 0
0 0 9 0 0 20
000704
000000
Enter the source of the graph
1
Enter the sink of the graph
6
The Max flow in the graph is 23
The Minimum Cut Set in the Graph is
2-4
5-6
5-4

Result:
Thus the java program for performing Linear Programming problems using java
has been executed successfully and the output is verified.

CP7111 Advanced Data Structures Laboratory

Page 23

EX. No:3

Implementation of algorithms using the hill climbing and


dynamic programming design techniques

EX.NO:3(a)

Hill Climbing

Aim:
To Create a hill climbing problem using java.
Algorithm :
1.start the program
2.Declare the Flight information
3. FlightInfo flights[]array holds the flight information.
4. number of entries in flight array
5. Initialize the flight database
6. Show the route and total distance.
7. If there is a flight between from and to, return the distance of flight;
8. otherwise, return 0.
9. Determine if there is a route between from and to.
10. Try another connection. f = find(from);
11. stop the program
Program:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;
//Flight information.
class FlightInfo {
String from;
String to;
int distance;
CP7111 Advanced Data Structures Laboratory

Page 24

boolean skip; // used in backtracking


FlightInfo(String f, String t, int d) {
from = f;
to = t;
distance = d;
skip = false;
}
}
public class Hill {
final int MAX = 100;
// This array holds the flight information.
FlightInfo flights[] = new FlightInfo[MAX];
int numFlights = 0; // number of entries in flight array
Stack btStack = new Stack(); // backtrack stack
public static void main(String args[]) {
String to, from;
Hill ob = new Hill();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
ob.setup();
try {
System.out.print("From? ");
from = br.readLine();
System.out.print("To? ");
to = br.readLine();
CP7111 Advanced Data Structures Laboratory

Page 25

ob.isflight(from, to);
if (ob.btStack.size() != 0)
ob.route(to);
} catch (IOException exc) {
System.out.println("Error on input.");
}
}
// Initialize the flight database.
Void setup() throws Exception
{
System.out.println(Enter the number of cities:);
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
int N= Integer.parseInt(in.readLine());
for(int i=0;i<N;i++)
{
System.out.println(Enter the Name of city(i+1));
String from = in.readLine();
System.out.println(Enter the no of Target Cities);
int targetCities=Integer.parseInt(in.readLine());
for(int t=0;t<targetCities;++t)
{
System.out.println(Enter name of target city+(t+1));
String to = in.readLine();
System.out.println(Enter Distance from+from+to+to);
int distance =Integer.parseInt(in.readLine());
addFlight(from,to,distance);
}
}
}
// Put flights into the database.
void addFlight(String from, String to, int dist) {
CP7111 Advanced Data Structures Laboratory

Page 26

if (numFlights < MAX) {


flights[numFlights] = new FlightInfo(from, to, dist);
numFlights++;
} else
System.out.println("Flight database full.\n");
}
// Show the route and total distance.
void route(String to) {
Stack rev = new Stack();
int dist = 0;
FlightInfo f;
int num = btStack.size();
// Reverse the stack to display route.
for (int i = 0; i < num; i++)
rev.push(btStack.pop());
for (int i = 0; i < num; i++) {
f = (FlightInfo) rev.pop();
System.out.print(f.from + " to ");
dist += f.distance;
}
System.out.println(to);
System.out.println("Distance is " + dist);
}
/*
* If there is a flight between from and to, return the distance of flight;
* otherwise, return 0.
*/
int match(String from, String to) {
for (int i = numFlights - 1; i > -1; i--) {
if (flights[i].from.equals(from) && flights[i].to.equals(to)
CP7111 Advanced Data Structures Laboratory

Page 27

&& !flights[i].skip) {
flights[i].skip = true; // prevent reuse
return flights[i].distance;
}
}
return 0; // not found
}
// Given from, find the farthest away connection.
FlightInfo find(String from) {
int pos = -1;
int dist = 0;
for (int i = 0; i < numFlights; i++) {
if (flights[i].from.equals(from) && !flights[i].skip) {
// Use the longest flight.
if (flights[i].distance> dist) {
pos = i;
dist = flights[i].distance;
}
}
}
if (pos != -1) {
flights[pos].skip = true; // prevent reuse
FlightInfo f = new FlightInfo(flights[pos].from, flights[pos].to,
flights[pos].distance);
return f;
}
return null;
}
// Determine if there is a route between from and to.
void isflight(String from, String to) {
CP7111 Advanced Data Structures Laboratory

Page 28

int dist;
FlightInfo f = null;
// See if at destination.
dist = match(from, to);
if (dist != 0) {
btStack.push(new FlightInfo(from, to, dist));
return;
}
// Try another connection. f = find(from);
if (f != null) {
btStack.push(new FlightInfo(from, to, f.distance));
isflight(f.to, to);
} else if (btStack.size() > 0) {
// Backtrack and try another connection.
f = (FlightInfo) btStack.pop();
isflight(f.from, f.to);
}
}
}
Output:
$ javac hillclimbing.java
$ java hillclimbing
Enter the number of cities :
7
Enter the Name of city 1
Chennai
Enter the no of Target cities
2
Enter the name of target city 1
Delhi
Enter Distance from Chennai to Delhi
4800
Enter the name of target city 2
Mumbai
CP7111 Advanced Data Structures Laboratory

Page 29

Enter Distance from Chennai to Delhi


2000
Enter the Name of city 2
Delhi
Enter the no of Target cities
2
Enter the name of target city 1
Singapore
Enter Distance from Delhi to Singapore
14800
Enter the name of target city 2
Mumbai
Enter Distance from Delhi to Mumbai
6000
Enter the Name of city 3
Mumbai
Enter the no of Target cities
2
Enter the name of target city 1
London
Enter Distance from Mumbai to London
16900
Enter the name of target city 2
New york
Enter Distance from Mumbai to New york
20420
Enter the no of Target cities
1
Enter the name of target city 1
LA
Enter Distance from New York to LA
740
Enter the Name of city 5
LA
Enter the no of Target cities
CP7111 Advanced Data Structures Laboratory

Page 30

0
Enter the Name of city 6
Singapore
Enter the no of Target cities
0
Enter the Name of city 7
London
Enter the no of Target cities
0
From? Chennai
To? London
Chennai to Delhi to Mumbai to London
Distance is 27700

Result:
Thus the java program hill climbing problem using java has been executed
successfully and the output is verified.
CP7111 Advanced Data Structures Laboratory

Page 31

EX.No:3(b)

Dynamic Programming

Aim:
To create a dynamic programming design techniques using knapsack problem.
Algorithm :
Step 1: Decompose the problem into smaller problems.
Step 2: Recursively define the value of an optimal solution in terms of solutions to
smaller problems.
Step 3: Bottom-up computing v[ i,w] (using iteration, not recursion)
Step 4: Given a knapsack with maximum capacity W, and a set S consisting of n
items
Step 5: Each item i has some weight wi and benefit value bi (all wi , bi and W are
integer values)
Program:
import java.util.Scanner;
public class Knapsack_DP
{
static int max(int a, int b)
{
return (a > b)? a : b;
}
static int knapSack(int W, int wt[], int val[], int n)
{
int i, w;
int [][]K = new int[n+1][W+1];
// Build table K[][] in bottom up manner
for (i = 0; i <= n; i++)
{
for (w = 0; w <= W; w++)
{
if (i==0 || w==0)
CP7111 Advanced Data Structures Laboratory

Page 32

K[i][w] = 0;
else if (wt[i-1] <= w)
K[i][w] = max(val[i-1] + K[i-1][w-wt[i-1]], K[i-1][w]);
else
K[i][w] = K[i-1][w];
}
}
return K[n][W];
}
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of items: ");
int n = sc.nextInt();
System.out.println("Enter the items weights: ");
int []wt = new int[n];
for(int i=0; i<n; i++)
wt[i] = sc.nextInt();
System.out.println("Enter the items values: ");
int []val = new int[n];
for(int i=0; i<n; i++)
val[i] = sc.nextInt();
System.out.println("Enter the maximum capacity: ");
int W = sc.nextInt();
System.out.println("The maximum value that can be put in a knapsack of
capacity W is: " + knapSack(W, wt, val, n));
sc.close();
}
}
CP7111 Advanced Data Structures Laboratory

Page 33

Output:
$ javac Knapsack_DP.java
$ java Knapsack_DP
Enter the number of items:
5
Enter the items weights:
01 56 42 78 12
Enter the items values:
50 30 20 10 50
Enter the maximum capacity:
150
The maximum value that can be put in a knapsack of capacity W is: 150

Result:
Thus the java program for performing dynamic programming design techniques
using knapsack problem has been executed successfully and the output is verified.

CP7111 Advanced Data Structures Laboratory

Page 34

EX. No:4 Implementation of recursive backtracking algorithms


Aim:
To Create a recursive backtracking algorithms by using N Queens problems.
Algorithm:
1. Place the queens column wise, start from the left most column
2. If all queens are placed.
3. return true and print the solution matrix.
4. Else
5. Try all the rows in the current column.
6. Check if queen can be placed here safely if yes mark the current cell in solution matrix as 1 and try to solve the rest of the problem recursively.
7. If placing the queen in above step leads to the solution return true.
8. If placing the queen in above step does not lead to the solution, BACKTRACK, mark the current cell in solution matrix as 0 and return
false.
9. If all the rows are tried and nothing worked, return false and
print NO SOLUTION.
Program:
public class Queens
{
public static boolean isConsistent(int[] q, int n) {
for (int i = 0; i < n; i++) {
if (q[i] == q[n])
return false;
if ((q[i] - q[n]) == (n - i)) return false;
if ((q[n] - q[i]) == (n - i)) return false;
}
return true;
}
public static void printQueens(int[] q) {
int n = q.length;
CP7111 Advanced Data Structures Laboratory

Page 35

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


for (int j = 0; j < n; j++) {
if (q[i] == j) StdOut.print("Q ");
else
StdOut.print("* ");
}
StdOut.println();
}
StdOut.println();
}
public static void enumerate(int n) {
int[] a = new int[n];
enumerate(a, 0);
}
public static void enumerate(int[] q, int k) {
int n = q.length;
if (k == n) printQueens(q);
else {
for (int i = 0; i < n; i++) {
q[k] = i;
if (isConsistent(q, k)) enumerate(q, k+1);
}
}
}
public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
enumerate(n);
}
}

CP7111 Advanced Data Structures Laboratory

Page 36

Output:
$ javac backtrack.java
$ java backtrack
% java Queens 4
*Q**
***Q
Q***
**Q*
**Q*
Q***
***Q
*Q**
% java Queens 8
Q*******
****Q***
*******Q
*****Q**
**Q*****
******Q*
*Q******
**Q****

Result:
Thus the java program for performing recursive backtracking algorithms by using
N Queens problems has been executed successfully and the output is verified.

CP7111 Advanced Data Structures Laboratory

Page 37

EX. No:5

Implementation of randomized algorithms.

Aim:
To Create a randomizedalgorithm by using the quick sort.
Algorithm:
1. Given array of some length n
2. Pick an element p of the array as the pivot (or halt if the array has size 0 or
1).
3. Split the array into sub-arrays LESS, EQUAL, and GREATER by comparing
each element to the pivot.
4. Recursively sort LESS and GREATER.
Program:
import java.util.Random;
public class Randomized_Quick_Sort
{
public static int N = 20;
public static int[] sequence = new int[N];
public static void QuickSort(int left, int right)
{
if (right - left <= 0)
return;
else
{
Random rand = new Random();
int pivotIndex = left + rand.nextInt(right - left + 1);
swap(pivotIndex, right);
int pivot = sequence[right];
int partition = partitionIt(left, right, pivot);
QuickSort(left, partition - 1);
QuickSort(partition + 1, right);
}
CP7111 Advanced Data Structures Laboratory

Page 38

}
public static int partitionIt(int left, int right, long pivot)
{
int leftPtr = left - 1;
int rightPtr = right;
while (true)
{
while (sequence[++leftPtr] < pivot);
while (rightPtr > 0 && sequence[--rightPtr] > pivot);
if (leftPtr >= rightPtr)
break;
else
swap(leftPtr, rightPtr);
}
swap(leftPtr, right);
return leftPtr;
}
public static void swap(int dex1, int dex2)
{
int temp = sequence[dex1];
sequence[dex1] = sequence[dex2];
sequence[dex2] = temp;
}
static void printSequence(int[] sorted_sequence)
{
for (int i = 0; i < sorted_sequence.length; i++)
System.out.print(sorted_sequence[i] + " ");
}
public static void main(String args[])
{
CP7111 Advanced Data Structures Laboratory

Page 39

System.out.println("Sorting of randomly generated numbers using


RANDOMIZED QUICK SORT");
Random random = new Random();
for (int i = 0; i < N; i++)
sequence[i] = Math.abs(random.nextInt(100));
System.out.println("\nOriginal Sequence: ");
printSequence(sequence);
System.out.println("\nSorted Sequence: ");
QuickSort(0, N - 1);
printSequence(sequence);
}
}
Output:
$ javac Randomized_Quick_Sort.java
$ java Randomized_Quick_Sort
Sorting of randomly generated numbers using RANDOMIZED QUICK SORT
Original Sequence:
98 95 22 64 77 49 11 98 56 63 84 18 9 68 4 69 2 20 68 4
Sorted Sequence:
2 4 4 9 11 18 20 22 49 56 63 64 68 68 69 77 84 95 98 98
Result:
Thus the java program for performing randomized algorithm by using the quick
sort has been executed successfully and the output is verified.

CP7111 Advanced Data Structures Laboratory

Page 40

EX. No:6

EX.NO:6(a)

Implementation Of Various Locking And


Synchronization Mechanisms For Concurrent Linked
Lists, Concurrent Queues, And Concurrent Stacks.
Concurrent Linked Lists

Aim:
To Create a Concurrent Linked Lists using java Program
Algorithm:
1. The linked list is always connected.
2. Nodes are only inserted after the last node of the linked list.
3. Nodes are only deleted from the beginning of the linked list.
4. Head always points to the first node in the linked list.
5. Tail always points to a node in the linked list
Program:
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());
CP7111 Advanced Data Structures Laboratory

Page 41

list.wait();
print(done with wait());
}
String item = (String) list.remove(0);
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+);
CP7111 Advanced Data Structures Laboratory

Page 42

}
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);
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)
{
}}
CP7111 Advanced Data Structures Laboratory

Page 43

Output:
$ List.java
$ java List
A: wait()
B: wait()
C: entering
C: added:Hello!
B: done with wait()
B: returned:Hello!
A: done with wait()
A: wait()
A: interrupted!

Result:
Thus the java program for performing Concurrent Linked Lists has been executed
successfully and the output is verified.

CP7111 Advanced Data Structures Laboratory

Page 44

Ex.NO: 6(b)

Concurrent Queues

Aim:
To Create a Concurrent Queue using java Program.
Algorithm:
1. Creates a ConcurrentLinkedQueue that is initially empty.
2. Creates a ConcurrentLinkedQueue initially containing the elements of the
given collection, added in traversal order of the collection's iterator.
3. Inserts the specified element at the tail of this queue.
4. Returns true if this queue contains the specified element.
5. Retrieves, but does not remove, the head of this queue, or returns null
6. if this queue is empty.
7. Removes a single instance of the specified element from this queue, if it is
present.
8. Returns the number of elements in this queue.
9. Returns an array containing all of the elements in this queue, in proper
10.sequence; the runtime type of the returned array is that of the
specified array.
Program:
import java.util.scanner;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class ConcurrentQueue
{
Public static void main(String[]args) throws
Exception
{
BlockingQueue<Integer> queue = new ArrayBlockingQueue<Integer>(1024);
Consumer consumer = new Consumer(queue);
new Thread(producer).start();
new Thread(consumer).start();
Thread.sleep(4000);
}
CP7111 Advanced Data Structures Laboratory

Page 45

}
protected BlockingQueue<Integer> queue = null;
public
Producer(BlockingQueue<Integer>queue)
{
this.queue = queue;
}
Public void run()
{
Try
{
System.out.println(Producer Has Started);
System.out.println(Enter three elements);
Scanner in = new
Scanner(System.in);
int one,two,three;
one=in.nextInt();
queue.put(one);
System.out.Println(Produced+one);
two= in.nextInt();
queue.put(two);
System.out.Println(Produced+two);
three= in.nextInt();
queue.put(three);
System.out.Println(Produced+three);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
}
Class
Consumer implements Runnable {
protected BlockingQueue<Integer> queue = null;
CP7111 Advanced Data Structures Laboratory

Page 46

public Consumer(BlockingQueue<Integer> queue)


{
this.queue = queue;
}
public void run()
{
try {
System.out.println(Consumer Has Started);
System.out.println(Consumed+queue.take());
System.out.println();
System.out.println(Consumed+queue.take());
System.out.println();
}
Catch
(InterruptedException e)
{
e.printStackTrace();
}

CP7111 Advanced Data Structures Laboratory

Page 47

Output:
$ javac QueueImpl.java
$ java QueueImpl
Producer Has Started
Enter three elements
Consumer Has started
3
Produced 3
Consumed 3
4
Produced 4
Consumed 4
5
Produced 5
Consumed 5

Result:
Thus the java program for concurrent queue has been executed successfully and
the output is verified.

CP7111 Advanced Data Structures Laboratory

Page 48

EX.NO:6(c)

Concurrent Stacks

Aim:
To Create a To Create a Concurrent Queue using java Program.
Algorithm:
1. Create a class for concurrent stack
2. Infer both the producer and consumer threads are synchronized.
3. Create a objects for both producer and consumer
4. Obtains a lock on the stack and the thread doesnt execute.
Program:
import java.util.Scanner;
import java.util.Stack;
public class ConcurrentStack
{
consumer threads are synchronized
public static void main(String[] args) throws Exception
{
Stack<Integer>stack = new
Stack<Integer>();
ProducerStack producer = new ProducerStack(stack);
ConsumerStack consumer = new ConsumerStack(stack);
new Thread(producer).start();
new Thread(consumer).start();
Thread.sleep(4000);
}
}
Class ProducerStack implements
Runnable {
protected Stack<Integer> stack = null;
public ProducerStack(Stack<Integer>stack)
{
this.stack =stack;
}
CP7111 Advanced Data Structures Laboratory

Page 49

public void run()


{
try
{
synchronized(stack)
{
System.out.println(Producer has started);
System.out.println(Enter 3 Elements);
Scanner in = new Scanner(System.in);
int one = in.nextInt();
stack.push(one);
System.out.println(Produced+one);
int two = in.nextInt();
stack.push(one);
System.out.println(Produced+two);
int three = in.nextInt();
stack.push(three);
System.out.println(Produced+three);
}
}
Catch(Exception e)
{
e.printStackTrace();
}
}
}
class ConsumerStack implements Runnable{
protected Stack<Integer> stack = null;
public
ConsumerStack(Stack<Integer>stack)
{
this.stack=stack;
}
public void run()
{
CP7111 Advanced Data Structures Laboratory

Page 50

try
{
System.out.println(Consumer has started);
System.out.println(Consumed+stack.pop());
System.out.println();
System.out.println(Consumed+stack.pop());
System.out.println();
System.out.println(Consumed+stack.pop());
System.out.println();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Output:
$ javac stack.java
$ java stack
Producer has Started
Enter 3 Elements
Consumer has started
34
Produced 34
21
Produced 21
67
Produced 67
Consumed 21
Consumed 34
Result:
Thus the java program for Concurrent stack has been executed successfully and the
output is verified.
CP7111 Advanced Data Structures Laboratory

Page 51

EX. No:7

Developing applications involving concurrency

SleepingBarber
Aim:
To Create a applications involving concurrency using sleeping barber problem.
Algorithm:
1. Create the semaphores.
2. Call the constructor with parameter 0.
3. Creating semaphores with zero initial permits.
4. Semaphore (1) constructs a binary semaphore.
5. Customer and barber thread is created.
6. Create a new barber shop.
7. Let the new simulation begin.
Program:
import java.util.concurrent.*;
public class SleepingBarber extends Thread {
public static Semaphore customers = new Semaphore(0);
public static Semaphore barber = new Semaphore(0);
public static Semaphore accessSeats = new Semaphore(1);
public static final int CHAIRS = 5;
public static int numberOfFreeSeats = CHAIRS;
class Customer extends Thread {
int iD;
boolean notCut=true;
public Customer(int i) {
iD = i;
}
public void run() {
while (notCut) {
try {
accessSeats.acquire();
CP7111 Advanced Data Structures Laboratory

Page 52

if (numberOfFreeSeats > 0) {
System.out.println("Customer " + this.iD + " just sat down.");
numberOfFreeSeats--;
customers.release();
accessSeats.release();
try {
barber.acquire();
notCut = false;
this.get_haircut();
}
catch (InterruptedException ex) {
}
}
else {
System.out.println("There are no free seats. Customer " + this.iD + " has left the
barbershop.");
accessSeats.release();
notCut=false;
}
}
catch (InterruptedException ex) {}
}
}
public void get_haircut(){
System.out.println("Customer " + this.iD + " is getting his hair cut");
try {
sleep(5050);
}
catch (InterruptedException ex) {}
}
}
class Barber extends Thread {
public Barber() {}
public void run() {
while(true) {
try {
CP7111 Advanced Data Structures Laboratory

Page 53

customers.acquire();
accessSeats.release();
numberOfFreeSeats++;
barber.release();
accessSeats.release();
this.cutHair();
} catch (InterruptedException ex) {}
}
}
public void cutHair(){
System.out.println("The barber is cutting hair");
try {
sleep(5000);
} catch (InterruptedException ex){ }
}
}
public static void main(String args[]) {
SleepingBarber barberShop = new SleepingBarber();
barberShop.start();
}
public void run(){
Barber giovanni = new Barber(); //Giovanni is the best barber ever
giovanni.start(); //Ready for another day of work
for (int i=1; i<16; i++) {
Customer aCustomer = new Customer(i);
aCustomer.start();
try {
sleep(2000);
} catch(InterruptedException ex) {};
}
}
}

CP7111 Advanced Data Structures Laboratory

Page 54

Output:
$ sleeping.java
$ java sleeping
Customer 1 just sat down
The barber is cutting hair
Customer 1 is getting his hair cut
Customer 2 just sat down
Customer 3 just sat down
The barber is cutting hair
Customer 2 is getting his hair cut
Customer 4 just sat down
The barber is cutting hair
Customer 3 is getting hair cut
The barber is cutting hair
Customer 4 is getting his hair cut

Result:
Thus the java program for performing applications involving concurrency using
sleeping barber problem has been executed successfully and the output is verified.
CP7111 Advanced Data Structures Laboratory

Page 55

You might also like