Identifying the Closest Unvisited Node
One of the key steps in Dijkstra's algorithm is to identify the closest unvisited node at each iteration. This is crucial for ensuring that the algorithm selects the node that will lead to the shortest overall path.
Maintaining a Priority Queue
To efficiently keep track of the unvisited nodes and their distances from the starting node, Dijkstra's algorithm typically uses a priority queue data structure. The priority queue stores the unvisited nodes, with the node having the smallest distance from the starting node at the front of the queue.
Here's an example of how you might implement this in Java using the PriorityQueue
class:
import java.util.PriorityQueue;
class Node implements Comparable<Node> {
int id;
int distance;
Node(int id, int distance) {
this.id = id;
this.distance = distance;
}
@Override
public int compareTo(Node other) {
return Integer.compare(this.distance, other.distance);
}
}
public class DijkstraExample {
public static void findShortestPath(int[][] graph, int startNode) {
int numNodes = graph.length;
PriorityQueue<Node> pq = new PriorityQueue<>();
int[] distances = new int[numNodes];
// Initialize distances and add starting node to the priority queue
for (int i = 0; i < numNodes; i++) {
distances[i] = Integer.MAX_VALUE;
}
distances[startNode] = 0;
pq.offer(new Node(startNode, 0));
while (!pq.isEmpty()) {
Node currentNode = pq.poll();
int currentId = currentNode.id;
// Skip visited nodes
if (distances[currentId] < currentNode.distance) {
continue;
}
// Update distances of neighboring nodes
for (int neighbor = 0; neighbor < numNodes; neighbor++) {
if (graph[currentId][neighbor] != 0) {
int newDistance = distances[currentId] + graph[currentId][neighbor];
if (newDistance < distances[neighbor]) {
distances[neighbor] = newDistance;
pq.offer(new Node(neighbor, newDistance));
}
}
}
}
// Print the final distances
for (int i = 0; i < numNodes; i++) {
System.out.println("Distance from " + startNode + " to " + i + ": " + distances[i]);
}
}
}
In this example, we create a custom Node
class that implements the Comparable
interface to allow the PriorityQueue
to sort the nodes based on their distance from the starting node. We then use the priority queue to efficiently select the closest unvisited node at each iteration of the algorithm.
By using a priority queue, Dijkstra's algorithm can find the shortest path between the starting node and all other nodes in the graph with a time complexity of O((V + E) log V), where V is the number of nodes and E is the number of edges in the graph.