forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
60 lines (58 loc) · 1.65 KB
/
Solution.java
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
class Solution {
private final int inf = 2000000000;
public int[][] modifiedGraphEdges(
int n, int[][] edges, int source, int destination, int target) {
long d = dijkstra(edges, n, source, destination);
if (d < target) {
return new int[0][];
}
boolean ok = d == target;
for (var e : edges) {
if (e[2] > 0) {
continue;
}
if (ok) {
e[2] = inf;
continue;
}
e[2] = 1;
d = dijkstra(edges, n, source, destination);
if (d <= target) {
ok = true;
e[2] += target - d;
}
}
return ok ? edges : new int[0][];
}
private long dijkstra(int[][] edges, int n, int src, int dest) {
int[][] g = new int[n][n];
long[] dist = new long[n];
Arrays.fill(dist, inf);
dist[src] = 0;
for (var f : g) {
Arrays.fill(f, inf);
}
for (var e : edges) {
int a = e[0], b = e[1], w = e[2];
if (w == -1) {
continue;
}
g[a][b] = w;
g[b][a] = w;
}
boolean[] vis = new boolean[n];
for (int i = 0; i < n; ++i) {
int k = -1;
for (int j = 0; j < n; ++j) {
if (!vis[j] && (k == -1 || dist[k] > dist[j])) {
k = j;
}
}
vis[k] = true;
for (int j = 0; j < n; ++j) {
dist[j] = Math.min(dist[j], dist[k] + g[k][j]);
}
}
return dist[dest];
}
}