Djikstra
Djikstra
int target;
int weight;
• The Node class is used to keep track of vertices along with the current known
distance from the source vertex during the algorithm's execution.
• It implements Comparable<Node> so that when inserted into a priority
queue, nodes are ordered based on their distance (smaller distances have
higher priority).
public static int[] dijkstra(List<List<Edge>> graph, int source) {
int V = graph.size();
int[] distances = new int[V];
while (!queue.isEmpty()) {
Node current = queue.poll();
int u = current.vertex;
// If a shorter path to v is found, update the distance and add it to the queue.
if (distances[u] + weight < distances[v]) {
distances[v] = distances[u] + weight;
queue.offer(new Node(v, distances[v]));
}
}
}
return distances;
}
• An array of size equal to the number of vertices (V) is created and filled with
Integer.MAX_VALUE (representing infinity). The distance to the source vertex is set to
0 because no cost is required to start from the source
• A priority queue (queue) is initialized to always pick the vertex with the smallest
known distance. The source node is added first with a distance of 0.
• If the distance stored in the node is greater than the current known distance (due to a
previously found shorter path), the node is skipped.
Relaxation Step:
• For each edge outgoing from the current vertex (u), the algorithm checks whether
going through u offers a shorter path to the neighbor vertex (v).
• If a shorter path is found, the distances[v] is updated and a new Node representing
vertex v with the updated distance is added to the queue
• When the queue is empty, the distances array contains the shortest path from the
source to every other vertex in the graph.
public static List<List<Edge>> createGraph(int vertices) {
List<List<Edge>> graph = new ArrayList<>();
for (int i = 0; i < vertices; i++) {
graph.add(new ArrayList<>());
}
return graph;
}
int source = 0;
int[] distances = dijkstra(graph, source);
• The dijkstra method is called with source = 0, which computes the shortest distance
from vertex 0 to all other vertices.
• The program prints the shortest distances from the source vertex to every other
vertex in a tabular format.