SlideShare a Scribd company logo
Please implement in Java. comments would be appreciated 5. Implement Algorithm 6.2 on your
system and run it on the problem instance of Exercise 1.
Solution
Branch and Bound:-
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Scanner;
publicclass BranchandBound
{
staticint[][] wt; // Matrix of edge
// weights
static String[] city; // Vector of city
// names
staticint n; // Dimension for wt
// and city
static ArrayList soln = new ArrayList();
staticint bestTour; // Initialized in
// init()
staticint blocked; // Ditto
staticboolean DEBUG = true; // Show
// accept/reject
// decisions
staticboolean VERBOSE = true; // Show all tours
// discovered
@SuppressWarnings("rawtypes")
privatestaticclass Tour implements Comparable
{
int[] soln;
int index; // In branch-and-bound, start of variable
int dist;
staticint nTours = 0;
// Best-first based on dist, or DFS based on maxheap of index
staticboolean DFS = true;
staticboolean DBG = true;
/*
* Presumable edges up to [index-1] have been verified before
* this constructor has been called. So compute the fixed
* distance from [0] up to [index-1] as dist.
*/
private Tour(int[] vect, int index, int[][] wt)
{
dist = 0;
for (int k = 1; k < index; k++)
// Add edges
dist += wt[vect[k - 1]][vect[k]];
if (index == n)
dist += wt[vect[n - 1]][vect[0]]; // Return edge
soln = newint[n]; // Deep copy
System.arraycopy(vect, 0, soln, 0, n);
this.index = index; // Index to permute
nTours++; // Count up # of tours
if (DBG)
System.out.printf("Idx %d: %s ", index, toString());
}
publicint compareTo(Object o)
{
Tour rt = (Tour) o;
int c1 = rt.index - this.index, c2 = this.dist - rt.dist;
if (DFS)
return c1 == 0 ? c2 : c1;
else
return c2;
}
public String toString()
{
StringBuilder val = new StringBuilder(city[soln[0]]);
for (int k = 1; k < n; k++)
val.append(", " + city[soln[k]]);
val.append(", " + city[soln[0]]);
val.append(String.format(" for %d", dist));
return val.toString();
}
}
privatestaticvoid init(Scanner inp)
{
int sub1, sub2;
String line;
n = inp.nextInt();
wt = newint[n][n];
city = new String[n];
// Initially, there are NO edges; hence -1.
for (sub1 = 0; sub1 < n; sub1++)
Arrays.fill(wt[sub1], -1);
inp.nextLine(); // Discard rest of first line
for (sub1 = 0; sub1 < n; sub1++)
city[sub1] = inp.nextLine();
Arrays.sort(city); // Just to be sure (binarySearch)
inp.nextLine(); // Discard blank spacing line;
blocked = 0; // Accumulate ALL weights for upper bound
while (inp.hasNext())
{
int head, tail;
int dist;
String src, dst;
line = inp.nextLine(); // E.g.: "George" "Pasco" 91
// Chop out the double-quoted substrings.
head = line.indexOf('"') + 1;
tail = line.indexOf('"', head);
src = line.substring(head, tail);
head = line.indexOf('"', tail + 1) + 1;
tail = line.indexOf('"', head);
dst = line.substring(head, tail);
dist = Integer.parseInt(line.substring(tail + 1).trim());
sub1 = Arrays.binarySearch(city, src);
sub2 = Arrays.binarySearch(city, dst);
wt[sub1][sub2] = wt[sub2][sub1] = dist;
blocked += dist;
}
blocked += blocked; // Double the total
bestTour = blocked; // And initialize bestTour
}
// Used below in generating permutations.
privatestaticvoid swap(int[] x, int p, int q)
{
int tmp = x[p];
x[p] = x[q];
x[q] = tmp;
}
// Generate the available tours by branch-and-bound.
// Generate the initial permutation vector, then save that state
// as the first examined in the branch-and-bound.
publicstaticvoid tour()
{
int[] vect = newint[n];
int start;
Queue work = new PriorityQueue();
// First permutation vector.
for (int k = 0; k < n; k++)
vect[k] = k;
start = Arrays.binarySearch(city, "Spokane");
if (start >= 0)
{
vect[start] = 0;
vect[0] = start;
}
work.add(new Tour(vect, 1, wt));
while (!work.isEmpty()) // Branch-and-bound loop
{
Tour current = work.poll();
int index = current.index;
vect = current.soln;
if (index == n) // I.e., Full permutation vector
{
if (wt[vect[n - 1]][vect[0]] > 0) // Return edge?
{
if (current.dist < bestTour) // Better than earlier?
{// Save the state in the list
bestTour = current.dist;
soln.add(current);
if (DEBUG)
System.out.println("Accept " + current);
}
elseif (DEBUG)
System.out.println("Too long: " + current);
}
elseif (DEBUG)
System.out.println("Invalid: " + current);
}
else
// Continue generating permutations
{
int k; // Loop variable
int hold; // Used in regenerating the original state
for (k = index; k < n; k++)
{
swap(vect, index, k);
if (wt[vect[index - 1]][vect[index]] < 0)
continue;
work.add(new Tour(vect, index + 1, wt));
}
// Restore original permutation
hold = vect[index];
for (k = index + 1; k < n; k++)
vect[k - 1] = vect[k];
vect[n - 1] = hold;
}
}
}
@SuppressWarnings("unchecked")
publicstaticvoid main(String[] args) throws Exception
{
String filename = args.length == 0 ? "RoadSet.txt" : args[0];
Scanner inp = new Scanner(new java.io.File(filename));
System.out.println("Data read from file " + filename);
init(inp);
tour();
if (VERBOSE)
{
System.out.println("Tours discovered:");
for (Tour opt : soln)
System.out.println(opt);
}
if (soln.size() == 0)
{
System.out.println("NO tours discovered. Exiting.");
System.exit(0);
}
System.out.println(Tour.nTours + " Tour objects generated.");
Collections.sort(soln);
System.out.println("Best tour: ");
System.out.println(soln.get(0));
}
}
Best First Search:-
import java.util.Comparator;
import java.util.InputMismatchException;
import java.util.PriorityQueue;
import java.util.Scanner;
publicclass BestFirstSearch
{
private PriorityQueue priorityQueue;
privateint heuristicvalues[];
privateint numberOfNodes;
publicstaticfinalint MAX_VALUE = 999;
public BestFirstSearch(int numberOfNodes)
{
this.numberOfNodes = numberOfNodes;
this.priorityQueue = new PriorityQueue(this.numberOfNodes,
new Vertex());
}
publicvoid bestFirstSearch(int adjacencyMatrix[][], int[] heuristicvalues,int source)
{
int evaluationNode;
int destinationNode;
int visited[] = newint [numberOfNodes + 1];
this.heuristicvalues = heuristicvalues;
priorityQueue.add(new Vertex(source, this.heuristicvalues[source]));
visited[source] = 1;
while (!priorityQueue.isEmpty())
{
evaluationNode = getNodeWithMinimumHeuristicValue();
destinationNode = 1;
System.out.print(evaluationNode + "t");
while (destinationNode <= numberOfNodes)
{
Vertex vertex = new Vertex(destinationNode,this.heuristicvalues[destinationNode]);
if ((adjacencyMatrix[evaluationNode][destinationNode] != MAX_VALUE
&& evaluationNode != destinationNode)&& visited[destinationNode] == 0)
{
priorityQueue.add(vertex);
visited[destinationNode] = 1;
}
destinationNode++;
}
}
}
privateint getNodeWithMinimumHeuristicValue()
{
Vertex vertex = priorityQueue.remove();
return vertex.node;
}
publicstaticvoid main(String... arg)
{
int adjacency_matrix[][];
int number_of_vertices;
int source = 0;
int heuristicvalues[];
Scanner scan = new Scanner(System.in);
try
{
System.out.println("Enter the number of vertices");
number_of_vertices = scan.nextInt();
adjacency_matrix = newint[number_of_vertices + 1][number_of_vertices + 1];
heuristicvalues = newint[number_of_vertices + 1];
System.out.println("Enter the Weighted Matrix for the graph");
for (int i = 1; i <= number_of_vertices; i++)
{
for (int j = 1; j <= number_of_vertices; j++)
{
adjacency_matrix[i][j] = scan.nextInt();
if (i == j)
{
adjacency_matrix[i][j] = 0;
continue;
}
if (adjacency_matrix[i][j] == 0)
{
adjacency_matrix[i][j] = MAX_VALUE;
}
}
}
for (int i = 1; i <= number_of_vertices; i++)
{
for (int j = 1; j <= number_of_vertices; j++)
{
if (adjacency_matrix[i][j] == 1 && adjacency_matrix[j][i] == 0)
{
adjacency_matrix[j][i] = 1;
}
}
}
System.out.println("Enter the heuristic values of the nodes");
for (int vertex = 1; vertex <= number_of_vertices; vertex++)
{
System.out.print(vertex + ".");
heuristicvalues[vertex] = scan.nextInt();
System.out.println();
}
System.out.println("Enter the source ");
source = scan.nextInt();
System.out.println("The graph is explored as follows");
BestFirstSearch bestFirstSearch = new BestFirstSearch(number_of_vertices);
bestFirstSearch.bestFirstSearch(adjacency_matrix, heuristicvalues,source);
} catch (InputMismatchException inputMismatch)
{
System.out.println("Wrong Input Format");
}
scan.close();
}
}
class Vertex implements Comparator
{
publicint heuristicvalue;
publicint node;
public Vertex(int node, int heuristicvalue)
{
this.heuristicvalue = heuristicvalue;
this.node = node;
}
public Vertex()
{
}
@Override
publicint compare(Vertex vertex1, Vertex vertex2)
{
if (vertex1.heuristicvalue < vertex2.heuristicvalue)
return -1;
if (vertex1.heuristicvalue > vertex2.heuristicvalue)
return 1;
return 0;
}
@Override
publicboolean equals(Object obj)
{
if (obj instanceof Vertex)
{
Vertex node = (Vertex) obj;
if (this.node == node.node)
{
returntrue;
}
}
returnfalse;
}
}

More Related Content

PDF
Complete the implementation of the Weighted Graph that we began in t.pdf
PPTX
Branch and bound method
PPTX
CPP Homework Help
PPT
Branch and bound
DOCX
Write a program that reads a connected graph from a file and displays.docx
PDF
i have written ths code as per your requirements with clear comments.pdf
PPT
fdocuments.in_branch-and-bound-design-and-analysis-of-alogorithm.ppt
PDF
Backtracking & branch and bound
Complete the implementation of the Weighted Graph that we began in t.pdf
Branch and bound method
CPP Homework Help
Branch and bound
Write a program that reads a connected graph from a file and displays.docx
i have written ths code as per your requirements with clear comments.pdf
fdocuments.in_branch-and-bound-design-and-analysis-of-alogorithm.ppt
Backtracking & branch and bound

Similar to Please implement in Java. comments would be appreciated 5.pdf (14)

PPTX
0 1 knapsack using branch and bound
PDF
knapsackusingbranchandbound
PDF
Program To change this license header, choose License Heade.pdf
PPTX
Data structure and algorithm
PPTX
TSP_Branch_and_Bound___Presentation.pptx
PPT
Branch and bound.ppt
PPT
Unit-2 Branch & Bound Design of Algorithms.ppt
PDF
JAVAImplement the DFS algorithm. The implementation should be able.pdf
PPT
Graphs
PPTX
Dynamic Programming in design and analysis .pptx
PPTX
OscaR.cbls3.0_V7
PPTX
ETCS262A-Analysis of design Algorithm.pptx
PDF
I have compilation errors that I'm struggling with in my code- please.pdf
PDF
Dijkstra's shortest path algorithm
0 1 knapsack using branch and bound
knapsackusingbranchandbound
Program To change this license header, choose License Heade.pdf
Data structure and algorithm
TSP_Branch_and_Bound___Presentation.pptx
Branch and bound.ppt
Unit-2 Branch & Bound Design of Algorithms.ppt
JAVAImplement the DFS algorithm. The implementation should be able.pdf
Graphs
Dynamic Programming in design and analysis .pptx
OscaR.cbls3.0_V7
ETCS262A-Analysis of design Algorithm.pptx
I have compilation errors that I'm struggling with in my code- please.pdf
Dijkstra's shortest path algorithm
Ad

More from fms12345 (20)

PDF
Exercise 1 (10 Points) Define a FixdLenStringList class that encaps.pdf
PDF
Describe the procedure you would use in the laboratory to determine .pdf
PDF
CHEM 1011 Discussion question 2ObjectiveTo learn more about the .pdf
PDF
Could you implement this please. I was told to use pointers as the d.pdf
PDF
A piece of malware is running on a Windows 7 machine via process inj.pdf
PDF
Company names Aerial Drones Surveillance Inc. Your company descript.pdf
PDF
2. The Lorenz curve measures inequality in person income distribution.pdf
PDF
13 808 PM docs.google.com Covalent Bonding and lonic Bonding study.pdf
PDF
1.The shrimping industry needs female shrimp for production purposes.pdf
PDF
Who are the stakeholders in an income statement and whySolution.pdf
PDF
Which company maintains natural habitats while B allowing us to live .pdf
PDF
When multiple strains of the same bacterial species are sequenced, w.pdf
PDF
What specialized cells line the inner cavity and move fluids through.pdf
PDF
What does the metaphor meaning for the Iron curtainSolutionIr.pdf
PDF
What are the major developmental milestones between infancy and todd.pdf
PDF
Using the Web or another research tool, search for alternative means.pdf
PDF
Using Array Approach, Linked List approach, and Delete Byte Approach.pdf
PDF
TV Guide magazine ran a cover photo for a story emphasizing Oprah Wi.pdf
PDF
Tim Tassopoulos, the chief operating officer for Chick-Fll-A applies .pdf
PDF
The Hydrolysis of the Hydrated Pb ion PboH (aq) + H200SolutionP.pdf
Exercise 1 (10 Points) Define a FixdLenStringList class that encaps.pdf
Describe the procedure you would use in the laboratory to determine .pdf
CHEM 1011 Discussion question 2ObjectiveTo learn more about the .pdf
Could you implement this please. I was told to use pointers as the d.pdf
A piece of malware is running on a Windows 7 machine via process inj.pdf
Company names Aerial Drones Surveillance Inc. Your company descript.pdf
2. The Lorenz curve measures inequality in person income distribution.pdf
13 808 PM docs.google.com Covalent Bonding and lonic Bonding study.pdf
1.The shrimping industry needs female shrimp for production purposes.pdf
Who are the stakeholders in an income statement and whySolution.pdf
Which company maintains natural habitats while B allowing us to live .pdf
When multiple strains of the same bacterial species are sequenced, w.pdf
What specialized cells line the inner cavity and move fluids through.pdf
What does the metaphor meaning for the Iron curtainSolutionIr.pdf
What are the major developmental milestones between infancy and todd.pdf
Using the Web or another research tool, search for alternative means.pdf
Using Array Approach, Linked List approach, and Delete Byte Approach.pdf
TV Guide magazine ran a cover photo for a story emphasizing Oprah Wi.pdf
Tim Tassopoulos, the chief operating officer for Chick-Fll-A applies .pdf
The Hydrolysis of the Hydrated Pb ion PboH (aq) + H200SolutionP.pdf
Ad

Recently uploaded (20)

PDF
RMMM.pdf make it easy to upload and study
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PPTX
GDM (1) (1).pptx small presentation for students
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
VCE English Exam - Section C Student Revision Booklet
PDF
Complications of Minimal Access Surgery at WLH
PPTX
Pharma ospi slides which help in ospi learning
PPTX
202450812 BayCHI UCSC-SV 20250812 v17.pptx
PDF
01-Introduction-to-Information-Management.pdf
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PDF
Computing-Curriculum for Schools in Ghana
PPTX
Lesson notes of climatology university.
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PDF
Microbial disease of the cardiovascular and lymphatic systems
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PDF
Anesthesia in Laparoscopic Surgery in India
RMMM.pdf make it easy to upload and study
Pharmacology of Heart Failure /Pharmacotherapy of CHF
Final Presentation General Medicine 03-08-2024.pptx
GDM (1) (1).pptx small presentation for students
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
O7-L3 Supply Chain Operations - ICLT Program
VCE English Exam - Section C Student Revision Booklet
Complications of Minimal Access Surgery at WLH
Pharma ospi slides which help in ospi learning
202450812 BayCHI UCSC-SV 20250812 v17.pptx
01-Introduction-to-Information-Management.pdf
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
Computing-Curriculum for Schools in Ghana
Lesson notes of climatology university.
human mycosis Human fungal infections are called human mycosis..pptx
Microbial diseases, their pathogenesis and prophylaxis
Microbial disease of the cardiovascular and lymphatic systems
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
Anesthesia in Laparoscopic Surgery in India

Please implement in Java. comments would be appreciated 5.pdf

  • 1. Please implement in Java. comments would be appreciated 5. Implement Algorithm 6.2 on your system and run it on the problem instance of Exercise 1. Solution Branch and Bound:- import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.PriorityQueue; import java.util.Queue; import java.util.Scanner; publicclass BranchandBound { staticint[][] wt; // Matrix of edge // weights static String[] city; // Vector of city // names staticint n; // Dimension for wt // and city static ArrayList soln = new ArrayList(); staticint bestTour; // Initialized in // init() staticint blocked; // Ditto staticboolean DEBUG = true; // Show // accept/reject // decisions staticboolean VERBOSE = true; // Show all tours // discovered
  • 2. @SuppressWarnings("rawtypes") privatestaticclass Tour implements Comparable { int[] soln; int index; // In branch-and-bound, start of variable int dist; staticint nTours = 0; // Best-first based on dist, or DFS based on maxheap of index staticboolean DFS = true; staticboolean DBG = true; /* * Presumable edges up to [index-1] have been verified before * this constructor has been called. So compute the fixed * distance from [0] up to [index-1] as dist. */ private Tour(int[] vect, int index, int[][] wt) { dist = 0; for (int k = 1; k < index; k++) // Add edges dist += wt[vect[k - 1]][vect[k]]; if (index == n) dist += wt[vect[n - 1]][vect[0]]; // Return edge soln = newint[n]; // Deep copy System.arraycopy(vect, 0, soln, 0, n); this.index = index; // Index to permute nTours++; // Count up # of tours if (DBG) System.out.printf("Idx %d: %s ", index, toString()); } publicint compareTo(Object o) { Tour rt = (Tour) o;
  • 3. int c1 = rt.index - this.index, c2 = this.dist - rt.dist; if (DFS) return c1 == 0 ? c2 : c1; else return c2; } public String toString() { StringBuilder val = new StringBuilder(city[soln[0]]); for (int k = 1; k < n; k++) val.append(", " + city[soln[k]]); val.append(", " + city[soln[0]]); val.append(String.format(" for %d", dist)); return val.toString(); } } privatestaticvoid init(Scanner inp) { int sub1, sub2; String line; n = inp.nextInt(); wt = newint[n][n]; city = new String[n]; // Initially, there are NO edges; hence -1. for (sub1 = 0; sub1 < n; sub1++) Arrays.fill(wt[sub1], -1); inp.nextLine(); // Discard rest of first line for (sub1 = 0; sub1 < n; sub1++) city[sub1] = inp.nextLine(); Arrays.sort(city); // Just to be sure (binarySearch) inp.nextLine(); // Discard blank spacing line; blocked = 0; // Accumulate ALL weights for upper bound while (inp.hasNext()) {
  • 4. int head, tail; int dist; String src, dst; line = inp.nextLine(); // E.g.: "George" "Pasco" 91 // Chop out the double-quoted substrings. head = line.indexOf('"') + 1; tail = line.indexOf('"', head); src = line.substring(head, tail); head = line.indexOf('"', tail + 1) + 1; tail = line.indexOf('"', head); dst = line.substring(head, tail); dist = Integer.parseInt(line.substring(tail + 1).trim()); sub1 = Arrays.binarySearch(city, src); sub2 = Arrays.binarySearch(city, dst); wt[sub1][sub2] = wt[sub2][sub1] = dist; blocked += dist; } blocked += blocked; // Double the total bestTour = blocked; // And initialize bestTour } // Used below in generating permutations. privatestaticvoid swap(int[] x, int p, int q) { int tmp = x[p]; x[p] = x[q]; x[q] = tmp; } // Generate the available tours by branch-and-bound. // Generate the initial permutation vector, then save that state // as the first examined in the branch-and-bound. publicstaticvoid tour() { int[] vect = newint[n]; int start;
  • 5. Queue work = new PriorityQueue(); // First permutation vector. for (int k = 0; k < n; k++) vect[k] = k; start = Arrays.binarySearch(city, "Spokane"); if (start >= 0) { vect[start] = 0; vect[0] = start; } work.add(new Tour(vect, 1, wt)); while (!work.isEmpty()) // Branch-and-bound loop { Tour current = work.poll(); int index = current.index; vect = current.soln; if (index == n) // I.e., Full permutation vector { if (wt[vect[n - 1]][vect[0]] > 0) // Return edge? { if (current.dist < bestTour) // Better than earlier? {// Save the state in the list bestTour = current.dist; soln.add(current); if (DEBUG) System.out.println("Accept " + current); } elseif (DEBUG) System.out.println("Too long: " + current); } elseif (DEBUG) System.out.println("Invalid: " + current); } else // Continue generating permutations {
  • 6. int k; // Loop variable int hold; // Used in regenerating the original state for (k = index; k < n; k++) { swap(vect, index, k); if (wt[vect[index - 1]][vect[index]] < 0) continue; work.add(new Tour(vect, index + 1, wt)); } // Restore original permutation hold = vect[index]; for (k = index + 1; k < n; k++) vect[k - 1] = vect[k]; vect[n - 1] = hold; } } } @SuppressWarnings("unchecked") publicstaticvoid main(String[] args) throws Exception { String filename = args.length == 0 ? "RoadSet.txt" : args[0]; Scanner inp = new Scanner(new java.io.File(filename)); System.out.println("Data read from file " + filename); init(inp); tour(); if (VERBOSE) { System.out.println("Tours discovered:"); for (Tour opt : soln) System.out.println(opt); } if (soln.size() == 0) { System.out.println("NO tours discovered. Exiting."); System.exit(0);
  • 7. } System.out.println(Tour.nTours + " Tour objects generated."); Collections.sort(soln); System.out.println("Best tour: "); System.out.println(soln.get(0)); } } Best First Search:- import java.util.Comparator; import java.util.InputMismatchException; import java.util.PriorityQueue; import java.util.Scanner; publicclass BestFirstSearch { private PriorityQueue priorityQueue; privateint heuristicvalues[]; privateint numberOfNodes; publicstaticfinalint MAX_VALUE = 999; public BestFirstSearch(int numberOfNodes) { this.numberOfNodes = numberOfNodes; this.priorityQueue = new PriorityQueue(this.numberOfNodes, new Vertex()); } publicvoid bestFirstSearch(int adjacencyMatrix[][], int[] heuristicvalues,int source) { int evaluationNode; int destinationNode; int visited[] = newint [numberOfNodes + 1]; this.heuristicvalues = heuristicvalues; priorityQueue.add(new Vertex(source, this.heuristicvalues[source]));
  • 8. visited[source] = 1; while (!priorityQueue.isEmpty()) { evaluationNode = getNodeWithMinimumHeuristicValue(); destinationNode = 1; System.out.print(evaluationNode + "t"); while (destinationNode <= numberOfNodes) { Vertex vertex = new Vertex(destinationNode,this.heuristicvalues[destinationNode]); if ((adjacencyMatrix[evaluationNode][destinationNode] != MAX_VALUE && evaluationNode != destinationNode)&& visited[destinationNode] == 0) { priorityQueue.add(vertex); visited[destinationNode] = 1; } destinationNode++; } } } privateint getNodeWithMinimumHeuristicValue() { Vertex vertex = priorityQueue.remove(); return vertex.node; } publicstaticvoid main(String... arg) { int adjacency_matrix[][]; int number_of_vertices; int source = 0; int heuristicvalues[];
  • 9. Scanner scan = new Scanner(System.in); try { System.out.println("Enter the number of vertices"); number_of_vertices = scan.nextInt(); adjacency_matrix = newint[number_of_vertices + 1][number_of_vertices + 1]; heuristicvalues = newint[number_of_vertices + 1]; System.out.println("Enter the Weighted Matrix for the graph"); for (int i = 1; i <= number_of_vertices; i++) { for (int j = 1; j <= number_of_vertices; j++) { adjacency_matrix[i][j] = scan.nextInt(); if (i == j) { adjacency_matrix[i][j] = 0; continue; } if (adjacency_matrix[i][j] == 0) { adjacency_matrix[i][j] = MAX_VALUE; } } } for (int i = 1; i <= number_of_vertices; i++) { for (int j = 1; j <= number_of_vertices; j++) { if (adjacency_matrix[i][j] == 1 && adjacency_matrix[j][i] == 0) { adjacency_matrix[j][i] = 1; } } }
  • 10. System.out.println("Enter the heuristic values of the nodes"); for (int vertex = 1; vertex <= number_of_vertices; vertex++) { System.out.print(vertex + "."); heuristicvalues[vertex] = scan.nextInt(); System.out.println(); } System.out.println("Enter the source "); source = scan.nextInt(); System.out.println("The graph is explored as follows"); BestFirstSearch bestFirstSearch = new BestFirstSearch(number_of_vertices); bestFirstSearch.bestFirstSearch(adjacency_matrix, heuristicvalues,source); } catch (InputMismatchException inputMismatch) { System.out.println("Wrong Input Format"); } scan.close(); } } class Vertex implements Comparator { publicint heuristicvalue; publicint node; public Vertex(int node, int heuristicvalue) { this.heuristicvalue = heuristicvalue; this.node = node; } public Vertex() {
  • 11. } @Override publicint compare(Vertex vertex1, Vertex vertex2) { if (vertex1.heuristicvalue < vertex2.heuristicvalue) return -1; if (vertex1.heuristicvalue > vertex2.heuristicvalue) return 1; return 0; } @Override publicboolean equals(Object obj) { if (obj instanceof Vertex) { Vertex node = (Vertex) obj; if (this.node == node.node) { returntrue; } } returnfalse; } }