From bd0a61da0a442c035c0e8aa755a74d09999a94eb Mon Sep 17 00:00:00 2001 From: marat Date: Thu, 11 Aug 2022 21:38:50 +0200 Subject: [PATCH] GO: 787. Cheapest Flights within K Stops --- go/787-Cheapest-Flights-Within-K-Stops.go | 38 +++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 go/787-Cheapest-Flights-Within-K-Stops.go diff --git a/go/787-Cheapest-Flights-Within-K-Stops.go b/go/787-Cheapest-Flights-Within-K-Stops.go new file mode 100644 index 000000000..663fd51e0 --- /dev/null +++ b/go/787-Cheapest-Flights-Within-K-Stops.go @@ -0,0 +1,38 @@ +func findCheapestPrice(n int, flights [][]int, src int, dst int, k int) int { + cost := make([]int, n) + + for i := 0; i < n; i++ { + cost[i] = math.MaxUint32 + } + + cost[src] = 0 + + for i := 0; i <= k; i++ { + temp := make([]int, n) + copy(temp, cost) + + for j := 0; j < len(flights); j++ { + from, to, price := flights[j][0], flights[j][1], flights[j][2] + + if cost[from] != math.MaxUint32 { + temp[to] = min(temp[to], cost[from]+price) + } + } + + cost = temp + } + + if cost[dst] == math.MaxUint32 { + return -1 + } + + return cost[dst] +} + +func min(x, y int) int { + if x > y { + return y + } + + return x +} \ No newline at end of file