-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdijkstra.java
More file actions
120 lines (63 loc) · 2.2 KB
/
Copy pathdijkstra.java
File metadata and controls
120 lines (63 loc) · 2.2 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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
package graphs;
import java.util.Scanner;
// single source shortest path.. should not have -ve weights.
// Time complexity
// O(V^2)---> for every V --> we do V times minvertex and V times neighbours=> V(2*V)
// adjacency list improves complexity: O(V+E)
// use priority queue for minVertex:O(logV)
// here sort needed for pq pairs(Vertex no,dist) sort based on distance(changes)
// O(V^2) ---> O(V(log+V)) ---> O((V+E)logV)
public class dijkstra {
public static int findMinVertex(int weights[], boolean visited[], int n) {
int minVertex = -1;
for (int i = 0; i < n; i++) {
if (visited[i] == false && (minVertex == -1 || weights[i] < weights[minVertex])) {
minVertex = i;
}
}
return minVertex;
}
public static void dijAlgo(int[][] edges, int V) {
int dist[] = new int[V];
boolean visited[] = new boolean[V];
for (int i = 0; i < V; i++) {
visited[i] = false;
dist[i] = Integer.MAX_VALUE;
}
dist[0] = 0;
for (int i = 0; i < V - 1; i++) {
int minVertex = findMinVertex(dist, visited, V);
visited[minVertex] = true;
for (int j = 0; j < V; j++) {
if (edges[minVertex][j] != 0 && visited[j] == false) {
int dis = dist[minVertex] + edges[minVertex][j];
if (dis < dist[j]) {
dist[j] = dis;
}
}
}
}
for (int i = 0; i < V; i++) {
System.out.println(i + " " + dist[i]);
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int V = sc.nextInt();
int E = sc.nextInt();
int edges[][] = new int[V][V];
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
edges[i][j] = 0;
}
}
for (int i = 0; i < E; i++) {
int f = sc.nextInt();
int s = sc.nextInt();
int w = sc.nextInt();
edges[f][s] = w;
edges[s][f] = w;
}
dijAlgo(edges, V);
}
}