From 320b5928b7ec7440148f3633cce1f800869ef199 Mon Sep 17 00:00:00 2001 From: MitaliJM <91389144+MitaliJM@users.noreply.github.com> Date: Sat, 28 Oct 2023 02:17:41 +0530 Subject: [PATCH] Create Dijkstra's Algorithm.java --- Dijkstra's Algorithm.java | 91 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 91 insertions(+) create mode 100644 Dijkstra's Algorithm.java diff --git a/Dijkstra's Algorithm.java b/Dijkstra's Algorithm.java new file mode 100644 index 0000000..003c00c --- /dev/null +++ b/Dijkstra's Algorithm.java @@ -0,0 +1,91 @@ +import java.util.*; +public class GFG { + private int dist[]; + private Set settled; + private PriorityQueue pq; + private int V; + List > adj; + public GFG(int V) + { + this.V = V; + dist = new int[V]; + settled = new HashSet(); + pq = new PriorityQueue(V, new Node()); + } + + public void dijkstra(List > adj, int src) + { + this.adj = adj; + + for (int i = 0; i < V; i++) + dist[i] = Integer.MAX_VALUE; + pq.add(new Node(src, 0)); + dist[src] = 0; + + while (settled.size() != V) { + if (pq.isEmpty()) + return; + int u = pq.remove().node; + if (settled.contains(u)) + continue; + settled.add(u); + + e_Neighbours(u); + } + } + + // Main driver method + public static void main(String arg[]) + { + + int V = 5; + int source = 0; + + List > adj + = new ArrayList >(); + for (int i = 0; i < V; i++) { + List item = new ArrayList(); + adj.add(item); + } + + adj.get(0).add(new Node(1, 9)); + adj.get(0).add(new Node(2, 6)); + adj.get(0).add(new Node(3, 5)); + adj.get(0).add(new Node(4, 3)); + + adj.get(2).add(new Node(1, 2)); + adj.get(2).add(new Node(3, 4)); + GFG dpq = new GFG(V); + dpq.dijkstra(adj, source); + System.out.println("The shorted path from node :"); + + for (int i = 0; i < dpq.dist.length; i++) + System.out.println(source + " to " + i + " is " + + dpq.dist[i]); + } +} +class Node implements Comparator { + + 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; + } +}