You are on page 1of 6

NAME : AVINASH TIWARI

ROLL NO,. :2100290110041

DAA LAB: Dijkstra Algorithm

CODE:
import java.util.ArrayList;

import java.util.Arrays;

import java.util.List;

import java.util.PriorityQueue;

class Edge {

int to, weight;

public Edge(int to, int weight) {

this.to = to;

this.weight = weight;

}
}

class Graph {

int vertices;

List<List<Edge>> adjacencyList;

public Graph(int vertices) {

this.vertices = vertices;

this.adjacencyList = new ArrayList<>(vertices);

for (int i = 0; i < vertices; i++) {

adjacencyList.add(new ArrayList<>());

public void addEdge(int from, int to, int weight) {

adjacencyList.get(from).add(new Edge(to, weight));


adjacencyList.get(to).add(new Edge(from, weight)); } public int[]
dijkstra(int start) {

int[] dist = new int[vertices]; Arrays.fill(dist,

Integer.MAX_VALUE);

dist[start] = 0;

PriorityQueue<Edge> minHeap = new PriorityQueue<>((a, b) ->

Integer.compare(a.weight, b.weight));

minHeap.add(new Edge(start, 0));

while (!minHeap.isEmpty()) { Edge

current = minHeap.poll();

int currentVertex = current.to;

int currentWeight = current.weight;

if (currentWeight > dist[currentVertex]) {

continue;
}

for (Edge neighbor : adjacencyList.get(currentVertex)) {

int newWeight = dist[currentVertex] + neighbor.weight;

if (newWeight < dist[neighbor.to]) {

dist[neighbor.to] = newWeight;

minHeap.add(new Edge(neighbor.to, newWeight));

return dist;

public class DijkstraAlgorithm {


public static void main(String[] args) {

int vertices = 5;

Graph graph = new Graph(vertices);

// Adding edges with their weights

graph.addEdge(0, 1, 2);

graph.addEdge(0, 3, 1);

graph.addEdge(1, 2, 3);

graph.addEdge(1, 3, 2);

graph.addEdge(2, 4, 1);

graph.addEdge(3, 4, 4);

int startVertex = 0;

// Running Dijkstra's algorithm


int[] shortestDistances = graph.dijkstra(startVertex); // Printing the
shortest distances from the start vertex

System.out.println("Shortest Distances from Vertex " + startVertex + ":");

for (int i = 0; i < shortestDistances.length; i++) {

System.out.println("To Vertex " + i + ": " + shortestDistances[i]);

OUTPUT:

Shortest Distances from Vertex 0:

To Vertex 0: 0

To Vertex 1: 2

To Vertex 2: 5

To Vertex 3: 1

To Vertex 4: 6

You might also like