Java Program to Implement Dijkstra’s Algorithm using Priority Queue

This Java program,to Implement Dijkstra’s algorithm using Priority Queue.Dijkstra’s algorithm is a graph search algorithm that solves the single-source shortest path problem for a graph with non-negative edge path costs, producing a shortest path tree.

Here is the source code of the Java program to implement Dijkstra’s algorithm using Priority Queue. The Java program is successfully compiled and run on a Linux system. The program output is also shown below.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
import java.util.HashSet;
import java.util.InputMismatchException;
import java.util.PriorityQueue;
import java.util.Scanner;
import java.util.Set;
  
public class DijkstraPriorityQueue
{
    private int distances[];
    private Set<Integer> settled;
    private PriorityQueue<Node> priorityQueue;
    private int number_of_nodes;
    private int adjacencyMatrix[][];
  
    public  DijkstraPriorityQueue(int number_of_nodes)
    {
        this.number_of_nodes = number_of_nodes;
        distances = new int[number_of_nodes + 1];
        settled = new HashSet<Integer>();
        priorityQueue = new PriorityQueue<Node>(number_of_nodes,new Node());
        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;
        }
  
        priorityQueue.add(new Node(source, 0));
        distances = 0;
        while (!priorityQueue.isEmpty())
        {
            evaluationNode = getNodeWithMinimumDistanceFromPriorityQueue();
            settled.add(evaluationNode);
            evaluateNeighbours(evaluationNode);
        }
    }
  
    private int getNodeWithMinimumDistanceFromPriorityQueue()
    {
        int node = priorityQueue.remove();
        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])
                    {
                        distances[destinationNode] = newDistance;
                    }
                    priorityQueue.add(new Node(destinationNode,distances[destinationNode]));
                }  
            }
        }
    }
  
    public static void main(String... arg)
    {
        int adjacency_matrix[][];
        int number_of_vertices;
        int source = 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)
                    {
                        adjacency_matrix[i][j] =  Integer.MAX_VALUE;
                    }
                }
            }
  
            System.out.println("Enter the source ");
            source = scan.nextInt();
  
            DijkstraPriorityQueue dijkstrasPriorityQueue = new DijkstraPriorityQueue(number_of_vertices);
            dijkstrasPriorityQueue.dijkstra_algorithm(adjacency_matrix, source);
  
            System.out.println("The Shorted Path to all nodes are ");
            for (int i = 1; i <= dijkstrasPriorityQueue.distances.length - 1; i++)
            {
                System.out.println(source + " to " + i + " is " + dijkstrasPriorityQueue.distances[i]);
            }
        } catch (InputMismatchException inputMismatch)
        {
            System.out.println("Wrong Input Format");
        }
        scan.close();
    }  
}
class Node implements Comparator<Node>
{
    public int node;
    public int cost;
  
    public Node()
    {
    }
  
    public Node(int node, int cost)
    {
        this.node = node;
        this.cost = cost;
    }
  
    @Override
    public int compare(Node node1, Node node2)
    {
        if (node1.cost < node2.cost)
            return -1;
        if (node1.cost > node2.cost)
            return 1;
        return 0;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
$javac DijkstraPriorityQueue.java
$java DijkstraPriorityQueue
Enter the number of vertices
5
Enter the Weighted Matrix for the graph
0 9 6 5 3
0 0 0 0 0
0 2 0 4 0
0 0 0 0 0
0 0 0 0 0
Enter the source
1
The Shorted Path to all nodes are
1 to 1 is 0
1 to 2 is 8
1 to 3 is 6
1 to 4 is 5
1 to 5 is 3

Related posts:

@Before vs @BeforeClass vs @BeforeEach vs @BeforeAll
Java Program to Apply Above-Below-on Test to Find the Position of a Point with respect to a Line
Java Program to Generate Random Partition out of a Given Set of Numbers or Characters
Java Program to Create a Minimal Set of All Edges Whose Addition will Convert it to a Strongly Conne...
Spring Boot - Scheduling
Service Registration with Eureka
An Intro to Spring Cloud Zookeeper
Transactions with Spring and JPA
Java Program to Implement D-ary-Heap
Java – Reader to String
Spring 5 and Servlet 4 – The PushBuilder
Different Ways to Capture Java Heap Dumps
Guide to Java 8’s Collectors
Java Program to Implement Hash Tables with Linear Probing
Tính đa hình (Polymorphism) trong Java
Spring Boot - Securing Web Applications
Java Program to Find Strongly Connected Components in Graphs
Đồng bộ hóa các luồng trong Java
Java Program to Find Nearest Neighbor Using Linear Search
Java Program to Implement Heap
Getting Started with Forms in Spring MVC
Spring REST with a Zuul Proxy
Notify User of Login From New Device or Location
Java Program to Compute Determinant of a Matrix
Java Program to Implement Lloyd’s Algorithm
Handling URL Encoded Form Data in Spring REST
Apache Tiles Integration with Spring MVC
Quick Guide to the Java StringTokenizer
Java Program to Implement Stack API
Spring Data JPA Delete and Relationships
Difference Between Wait and Sleep in Java
Java Program to Check if a Point d lies Inside or Outside a Circle Defined by Points a, b, c in a Pl...