diff --git a/djikstra.java b/djikstra.java new file mode 100644 index 0000000..43cb072 --- /dev/null +++ b/djikstra.java @@ -0,0 +1,164 @@ +import java.util.Scanner; +import java.util.Arrays; + +class Node{ + int val; + int weight; + Node next; + + public Node(int val,int weight){ + this.val = val; + this.weight = weight; + this.next = null; + } +} + +class Graph{ + + public Node[] CreateGraph(int n){ + Node[] Graph = new Node[n]; + return Graph; + } + + /* This Function adds Edge between the Source and Destination */ + + public void AddEdge(Node[] Graph,int src,int dest,int weight){ + + + if(Graph[src] == null){ + + Graph[src] = new Node(dest,weight); + return; + + } + + else{ + + Node temp = new Node(dest,weight); + + temp.next = Graph[src]; + + Graph[src] = temp; + + } + + } + + /* This Function returns the Index of the Node that has the Least Shortest Distance and is UnVisited. */ + + public int MinIndex(int[] dist,boolean[] visited){ + int min = Integer.MAX_VALUE; + int min_index = -1; + + for(int i = 0;i dist[i]){ + min = dist[i]; + min_index = i; + } + } + + return min_index; + } + +} + + +public class djikstra { + public static void main(String[] args) { + + Scanner scan = new Scanner(System.in); + + Graph g = new Graph(); + + + System.out.print("Enter the Number of Nodes in the Graph : "); + + int num = scan.nextInt(); + + Node[] Graph = g.CreateGraph(num); + + System.out.print("Enter the Total Number of Edges in the Graph : "); + + int edges = scan.nextInt(); + + System.out.println("Now Enter all the Edges as Source Destination Weight"); + + /* Storing the edges */ + + for(int i = 0;i dist[min_index] + temp.weight && !visited[temp.val]){ + dist[temp.val] = dist[min_index] + temp.weight; + } + + temp = temp.next; + + } + } + + /* Printing the Shortest Distances from the Start Node to all the other Nodes */ + + for(int i = 0;i