Java Program to Implement Uniform-Cost Search

This Java program,Implements Uniform Cost Search.In computer science, uniform-cost search (UCS) is a tree search algorithm used for traversing or searching a weighted tree, tree structure, or graph. The search begins at the root node. The search continues by visiting the next node which has the least total cost from the root. Nodes are visited in this manner until a goal state is reached.

Here is the source code of the Java program implements uniform cost search. The Java program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. import java.util.Comparator;
  2. import java.util.HashSet;
  3. import java.util.InputMismatchException;
  4. import java.util.Iterator;
  5. import java.util.LinkedList;
  6. import java.util.PriorityQueue;
  7. import java.util.Scanner;
  8. import java.util.Set;
  9.  
  10. public class UniformCostSearch
  11. {
  12.     private PriorityQueue<Node> priorityQueue;
  13.     private Set<Integer> settled;
  14.     private int distances[];
  15.     private int numberOfNodes;
  16.     private int adjacencyMatrix[][];
  17.     private LinkedList<Integer> path;
  18.     private int[] parent;
  19.     private int source, destination;
  20.     public static final int MAX_VALUE = 999; 
  21.  
  22.     public UniformCostSearch(int numberOfNodes)
  23.     {
  24.         this.numberOfNodes = numberOfNodes;
  25.         this.settled = new HashSet<Integer>();
  26.         this.priorityQueue = new PriorityQueue<>(numberOfNodes, new Node());
  27.         this.distances = new int[numberOfNodes + 1];
  28.         this.path = new LinkedList<Integer>();
  29.         this.adjacencyMatrix = new int[numberOfNodes + 1][numberOfNodes + 1]; 
  30.         this.parent = new int[numberOfNodes + 1];
  31.     }
  32.  
  33.     public int uniformCostSearch(int adjacencyMatrix[][], int source, int destination)
  34.     {
  35.         int evaluationNode;
  36.         this.source = source;
  37.         this.destination = destination;
  38.  
  39.         for (int i = 1; i <= numberOfNodes; i++)
  40.         {
  41.             distances[i] = MAX_VALUE;
  42.         }
  43.  
  44.         for (int sourcevertex = 1; sourcevertex <= numberOfNodes; sourcevertex++)
  45.         {
  46.             for (int destinationvertex = 1; destinationvertex <= numberOfNodes; destinationvertex++)
  47.             {
  48.                 this.adjacencyMatrix[sourcevertex][destinationvertex] =
  49.                        adjacencyMatrix[sourcevertex[destinationvertex];
  50. 	    }
  51.         }
  52.  
  53.         priorityQueue.add(new Node(source, 0));
  54.         distances[source] = 0;
  55.  
  56.         while (!priorityQueue.isEmpty())
  57.         {
  58.             evaluationNode = getNodeWithMinDistanceFromPriorityQueue();
  59.             System.out.println("The eval Node is " + evaluationNode);
  60.             if (evaluationNode == destination)
  61.             {
  62.                 return distances[destination];
  63.             } 
  64.             settled.add(evaluationNode);
  65.             addFrontiersToQueue(evaluationNode);
  66.         }
  67.         return distances[destination];
  68.     }
  69.  
  70.     private void addFrontiersToQueue(int evaluationNode)
  71.     {
  72.         for (int destination = 1; destination <= numberOfNodes; destination++)
  73.         {
  74.             if (!settled.contains(destination))
  75.             {
  76.                 if (adjacencyMatrix[evaluationNode][destination] != MAX_VALUE)
  77.                 {
  78.                     if (distances[destination] > adjacencyMatrix[evaluationNode][destination]  
  79.                                     + distances[evaluationNode])
  80.                     {
  81.                         distances[destination] = adjacencyMatrix[evaluationNode][destination]	
  82.                                                + distances[evaluationNode]; 				 		
  83.                         parent[destination] = evaluationNode;
  84.                     }
  85.  
  86.                     Node node = new Node(destination, distances[destination]);
  87.                     if (priorityQueue.contains(node))
  88.                     {
  89.                         priorityQueue.remove(node);
  90.                     }
  91.                     priorityQueue.add(node);
  92.                 }
  93.             }
  94.         }
  95.     }
  96.  
  97.     private int getNodeWithMinDistanceFromPriorityQueue()
  98.     {
  99.         Node node = priorityQueue.remove();
  100.         return node.node;
  101.     }
  102.  
  103.     public void printPath()
  104.     {
  105.         path.add(destination);
  106.         boolean found = false;
  107.         int vertex = destination;
  108.         while (!found)
  109.         {
  110.             if (vertex == source)
  111.             {
  112.                 found = true;
  113.                 continue;
  114.             }
  115.             path.add(parent[vertex]);
  116.             vertex = parent[vertex];
  117.         }
  118.  
  119.         System.out.println("The Path between " + source + " and " + destination+ " is ");
  120.         Iterator<Integer> iterator = path.descendingIterator();
  121.         while (iterator.hasNext())
  122.         {
  123.             System.out.print(iterator.next() + "\t");
  124.         }
  125.     }
  126.  
  127.     public static void main(String... arg)
  128.     {
  129.         int adjacency_matrix[][];
  130.         int number_of_vertices;
  131.         int source = 0;
  132.         int destination = 0;
  133.         int distance;
  134.         Scanner scan = new Scanner(System.in);
  135.         try
  136.         {
  137.             System.out.println("Enter the number of vertices");
  138.             number_of_vertices = scan.nextInt();
  139.  
  140.             adjacency_matrix = new int[number_of_vertices + 1][number_of_vertices + 1];
  141.             System.out.println("Enter the Weighted Matrix for the graph");
  142.             for (int i = 1; i <= number_of_vertices; i++)
  143.             {
  144.                 for (int j = 1; j <= number_of_vertices; j++)
  145.                 {
  146.                     adjacency_matrix[i][j] = scan.nextInt();
  147.                     if (i == j)
  148.                     {
  149.                         adjacency_matrix[i][j] = 0;
  150.                         continue;
  151.                     }
  152.                     if (adjacency_matrix[i][j] == 0)
  153.                     {
  154.                         adjacency_matrix[i][j] = MAX_VALUE;
  155.                     }
  156.                 }
  157.             }
  158.  
  159.             System.out.println("Enter the source ");
  160.             source = scan.nextInt();
  161.  
  162.             System.out.println("Enter the destination");
  163.             destination = scan.nextInt();
  164.  
  165.             UniformCostSearch uniformCostSearch = new UniformCostSearch(number_of_vertices);
  166.             distance = uniformCostSearch.uniformCostSearch(adjacency_matrix,source, destination);
  167.             uniformCostSearch.printPath();
  168.  
  169.             System.out.println("\nThe Distance between source " + source +
  170.                           " and destination " + destination + " is " + distance);
  171.  
  172.         } catch (InputMismatchException inputMismatch)
  173.         {
  174.             System.out.println("Wrong Input Format");
  175.         }
  176.         scan.close();
  177.     }
  178. }
  179.  
  180. class Node implements Comparator<Node>
  181. {
  182.     public int node;
  183.     public int cost;
  184.  
  185.     public Node()
  186.     {
  187.  
  188.     }
  189.  
  190.     public Node(int node, int cost)
  191.     {
  192.         this.node = node;
  193.         this.cost = cost;
  194.     }
  195.  
  196.     @Override
  197.     public int compare(Node node1, Node node2)
  198.     {
  199.         if (node1.cost < node2.cost)
  200.             return -1;
  201.         if (node1.cost > node2.cost)
  202.             return 1;
  203.         if (node1.node < node2.node)
  204.             return -1;
  205.         return 0;
  206.     }
  207.  
  208.     @Override
  209.     public boolean equals(Object obj)
  210.     {
  211.         if (obj instanceof Node)
  212.         {
  213.             Node node = (Node) obj;
  214.             if (this.node == node.node)
  215.             {
  216.                 return true;
  217.             }
  218.         }
  219.         return false;
  220.     }
  221. }


$javac UniformCostSearch.java
$java UniformCostSearch
Enter the number of vertices
7
Enter the Weighted Matrix for the graph
0 5 0 3 0 0 0
0 0 1 0 0 0 0
0 0 0 0 6 0 8
0 0 0 0 2 2 0
0 4 0 0 0 0 0
0 0 0 0 0 0 3
0 0 0 0 4 0 0
Enter the source 
1
Enter the destination
7
The Path between 1 and 7 is 
1	4	6	7	
The Distance between source 1 and destination 7 is 8

Sanfoundry Global Education & Learning Series – 1000 Java Programs.

advertisement
advertisement
If you wish to look at all Java Programming examples, go to Java Programs.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.