forked from Kraken-ops/Hacktoberfest-2022
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdijkstra.java
More file actions
75 lines (55 loc) · 1.53 KB
/
Copy pathdijkstra.java
File metadata and controls
75 lines (55 loc) · 1.53 KB
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
65
66
67
68
69
70
71
72
73
74
75
import java.util.Scanner;
public class Solution {
public static void dijkstra(int[][] edges) {
int[] distance = new int[edges.length];
boolean[] visited = new boolean[edges.length];
distance[0] = 0;
for(int i=1;i<distance.length;i++) {
distance[i] = Integer.MAX_VALUE;
}
for(int i=1;i<edges.length;i++) {
int minVertex = findMinDistanceUnvisitedVertex( distance,visited);
visited[minVertex] = true;
for(int j=0;j<edges.length;j++) {
if(!visited[j] && edges[minVertex][j]!=0) {
int d = edges[minVertex][j] + distance[minVertex];
if( distance[j] > d ) {
distance[j] = d;
}
}
}
}
for(int i=0;i<distance.length;i++) {
System.out.println( i+" " + distance[i] );
}
}
private static int findMinDistanceUnvisitedVertex(int[] distance ,boolean[] visited) {
int minIndex = 0;
int min = Integer.MAX_VALUE;
for(int i=0;i<distance.length;i++) {
if(!visited[i] && min > distance[i] ) {
min = distance[i];
minIndex = i;
}
}
return minIndex;
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int E = s.nextInt();
int[][] edges = new int[n][n];
for(int i=0;i<E;i++) {
int sv = s.nextInt();
int ev = s.nextInt();
int weight = s.nextInt();
edges[sv][ev] = weight;
edges[ev][sv] = weight;
}
dijkstra(edges);
/* Write Your Code Here
* Complete the Rest of the Program
* You have to take input and print the output yourself
*/
}
}