Skip to content

Commit 67a8422

Browse files
authored
Added 787 in Java (#69)
* Add 787 java. Contributed by @spattk
1 parent fefe70c commit 67a8422

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
class Solution {
2+
//using bellman ford
3+
4+
public void computePrice(int[][]flights, int[] prices, int [] temp){
5+
for(int[] flight: flights){
6+
int u = flight[0];
7+
int v = flight[1];
8+
int price = flight[2];
9+
10+
if(prices[u] != Integer.MAX_VALUE){
11+
if(prices[u] + price < temp[v]){
12+
temp[v] = prices[u] + price;
13+
}
14+
}
15+
}
16+
}
17+
18+
public void copyTempToPrice(int[] prices, int[] temp){
19+
for(int i=0; i<prices.length; i++){
20+
prices[i] = temp[i];
21+
}
22+
}
23+
24+
public int findCheapestPrice(int n, int[][] flights, int src, int dst, int k) {
25+
int[] prices = new int[n];
26+
int[] temp = new int[n];
27+
28+
Arrays.fill(prices, Integer.MAX_VALUE);
29+
Arrays.fill(temp, Integer.MAX_VALUE);
30+
31+
prices[src] = 0;
32+
temp[src] = 0;
33+
34+
for(int i=0; i<=k; i++){
35+
computePrice(flights, prices, temp);
36+
copyTempToPrice(prices, temp);
37+
}
38+
39+
return prices[dst] == Integer.MAX_VALUE ? -1 : prices[dst];
40+
}
41+
}

0 commit comments

Comments
 (0)