0% found this document useful (0 votes)
4 views9 pages

Djikstra

The document describes the implementation of Dijkstra's algorithm using Java, including the definitions of the Edge and Node classes. It outlines how to create a graph, add edges, and compute the shortest distances from a source vertex to all other vertices. The main method demonstrates building a graph and printing the shortest distances from the source vertex to each vertex.

Uploaded by

ananyakrish69
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views9 pages

Djikstra

The document describes the implementation of Dijkstra's algorithm using Java, including the definitions of the Edge and Node classes. It outlines how to create a graph, add edges, and compute the shortest distances from a source vertex to all other vertices. The main method demonstrates building a graph and printing the shortest distances from the source vertex to each vertex.

Uploaded by

ananyakrish69
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 9

static class Edge {

int target;
int weight;

Edge(int target, int weight) {


this.target = target;
this.weight = weight;
}
}

• The Edge class represents a connection (edge) from


one vertex to another.
• target: The vertex that this edge leads to.
• weight: The cost or weight associated with traversing
static class Node implements Comparable<Node> {
int vertex;
int distance;

Node(int vertex, int distance) {


this.vertex = vertex;
this.distance = distance;
}

public int compareTo(Node other) {


return Integer.compare(this.distance, other.distance);
}
}

• 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];

// Initialize all distances as infinity


Arrays.fill(distances, Integer.MAX_VALUE);
distances[source] = 0;

// PriorityQueue to select the vertex with the smallest known distance


PriorityQueue<Node> queue = new PriorityQueue<>();
queue.offer(new Node(source, 0));

while (!queue.isEmpty()) {
Node current = queue.poll();
int u = current.vertex;

// Skip this node if we've already found a better path


if (current.distance > distances[u]) {
continue;
}
// Explore each edge (neighbor) from the current vertex.
for (Edge edge : graph.get(u)) {
int v = edge.target;
int weight = edge.weight;

// 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;
}

• This method creates an empty graph represented as


an adjacency list.
• It creates a list of lists where each inner list will hold
the edges originating from a vertex.
public static void addEdge(List<List<Edge>> graph, int
u, int v, int weight) {
graph.get(u).add(new Edge(v, weight));
graph.get(v).add(new Edge(u, weight)); // For
undirected graph
}

• Adds an edge between two vertices for an


undirected graph.

• It adds an edge from u to v and another edge


from v to u, each with the same weight.
public static void main(String[] args) {
int vertices = 5; // Total vertices in the graph
List<List<Edge>> graph = createGraph(vertices);

// Build the graph by adding edges.


addEdge(graph, 0, 1, 10);
addEdge(graph, 0, 2, 3);
addEdge(graph, 1, 2, 1);
addEdge(graph, 1, 3, 2);
addEdge(graph, 2, 1, 4);
addEdge(graph, 2, 3, 8);
addEdge(graph, 2, 4, 2);
addEdge(graph, 3, 4, 7);
addEdge(graph, 4, 3, 9);

int source = 0;
int[] distances = dijkstra(graph, source);

// Print the shortest distances from the source to each vertex.


System.out.println("Vertex\tDistance from Source " + source);
for (int i = 0; i < distances.length; i++) {
System.out.println(i + "\t\t" + distances[i]);
}
}
• The addEdge method is used to build the graph. Since the graph is undirected, each
call to addEdge adds a bidirectional connection between vertices.

• 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.

You might also like