×
NOTE!
Click on MENU to Browse between Subjects...
Advertisement
DESIGN AND ANALYSIS OF ALGORITHMS LABORATORY
(Effective from the academic year 2018 -2019)
SEMESTER - IV
Course Code 18CSL47
CIE Marks 40
Number of Contact Hours/Week 0:2:2
SEE Marks 60
Total Number of Lab Contact Hours 36
Exam Hours 03
Advertisement
Experiments 7
From a given vertex in a weighted connected graph, find shortest paths to other vertices using Dijkstra's algorithm. Write the program in Java.
Advertisement
Advertisement
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 | import java.util.Scanner; public class Diji { public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.println("Enter Number of Vertices"); int n = scan.nextInt(); int adj[][] = new int[n][n]; System.out.println("Enter Adjacency Matrix"); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { adj[i][j] = scan.nextInt(); } } System.out.println("Enter Source vertex"); int src = scan.nextInt(); int[] dist = dijkstra(adj, src); for (int i = 0; i < n; i++) { if ((src - 1) == i) { continue; } System.out.println("Shortest Distance from " + src + " to " + (i + 1) + " is " + dist[i]); } scan.close(); } static int[] dijkstra(int adj[][], int src) { int n = adj.length; int[] dist = new int[n]; boolean[] visited = new boolean[n]; int min_dist, unvis = -1; for (int i = 0; i < n; i++) { dist[i] = adj[src - 1][i]; visited[i] = false; } visited[src - 1] = true; for (int i = 1; i < n; i++) { min_dist = Integer.MAX_VALUE; for (int j = 0; j < n; j++) { if (!visited[j] && dist[j] < min_dist) { unvis = j; min_dist = dist[j]; } } visited[unvis] = true; for (int v = 0; v < n; v++) { if (!visited[v] && dist[unvis] + adj[unvis][v] < dist[v]) { dist[v] = dist[unvis] + adj[unvis][v]; } } } return dist; } } |
Advertisement
Fig 7.1: Output .
×
Note
Please Share the website link with Your Friends and known Students...
-ADMIN
-ADMIN
×
Note
Page Number is specified to navigate between Pages...
T = Text book
QB = Question Bank
AS = Amswer Script
-ADMIN
T = Text book
QB = Question Bank
AS = Amswer Script
-ADMIN
Advertisement