Skip to content

Commit 53d48ed

Browse files
authored
Merge pull request neetcode-gh#635 from Rixant/743-network-delay-time
java: Created network delay time
2 parents 03bd29c + 77daeb7 commit 53d48ed

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

java/743-Network-Delay-Time.java

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
// Bellman Ford ALgorithm
2+
// Time Complexty (n * t) | Space Complexity O(n) where t is the length of times
3+
class Solution {
4+
public int networkDelayTime(int[][] times, int n, int k) {
5+
6+
// initialize an array with max value of size n
7+
int[] paths = new int[n];
8+
Arrays.fill(paths, Integer.MAX_VALUE);
9+
10+
paths[k - 1] = 0;
11+
12+
for (int i = 0; i < n; i++){
13+
14+
// make a copy of paths
15+
int[] temp = new int[n];
16+
temp = Arrays.copyOf(paths, paths.length);
17+
18+
// loop through times
19+
for(int j = 0; j < times.length; j ++){
20+
21+
int src = times[j][0]; // source
22+
int tgt = times[j][1]; // target
23+
int time = times[j][2]; // time
24+
25+
if (temp[src - 1] != Integer.MAX_VALUE && temp[src - 1] + time < temp[tgt - 1]){
26+
temp[tgt - 1] = temp[src - 1] + time;
27+
}
28+
29+
}
30+
31+
// set paths to temp
32+
paths = temp;
33+
34+
}
35+
36+
int result= Integer.MIN_VALUE;
37+
38+
// calculate max value
39+
for(int i = 0; i < n;i++){
40+
if(paths[i] == Integer.MAX_VALUE) {
41+
return -1;
42+
}
43+
result = Math.max(result, paths[i]);
44+
}
45+
46+
// return result
47+
return result;
48+
49+
}
50+
}

0 commit comments

Comments
 (0)