File tree Expand file tree Collapse file tree 1 file changed +50
-0
lines changed Expand file tree Collapse file tree 1 file changed +50
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments