| | 1 | | // -------------------------------------------------------------------------------- |
| | 2 | | // Copyright (C) 2025 Eugene Eremeev (also known as Yevhenii Yeriemeieiv). |
| | 3 | | // All Rights Reserved. |
| | 4 | | // -------------------------------------------------------------------------------- |
| | 5 | | // This software is the confidential and proprietary information of Eugene Eremeev |
| | 6 | | // (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not |
| | 7 | | // disclose such Confidential Information and shall use it only in accordance with |
| | 8 | | // the terms of the license agreement you entered into with Eugene Eremeev (also |
| | 9 | | // known as Yevhenii Yeriemeieiv). |
| | 10 | | // -------------------------------------------------------------------------------- |
| | 11 | |
|
| | 12 | | namespace LeetCode.Algorithms.CheapestFlightsWithinKStops; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class CheapestFlightsWithinKStopsBellmanFord : ICheapestFlightsWithinKStops |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O (k * E), where k is the number of stops allowed and E is the number of edges(flights). |
| | 19 | | /// Space complexity - O (n) |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="n"></param> |
| | 22 | | /// <param name="flights"></param> |
| | 23 | | /// <param name="src"></param> |
| | 24 | | /// <param name="dst"></param> |
| | 25 | | /// <param name="k"></param> |
| | 26 | | /// <returns></returns> |
| | 27 | | public int FindCheapestPrice(int n, int[][] flights, int src, int dst, int k) |
| 4 | 28 | | { |
| 4 | 29 | | var cost = new int[n]; |
| | 30 | |
|
| 4 | 31 | | Array.Fill(cost, int.MaxValue); |
| | 32 | |
|
| 4 | 33 | | cost[src] = 0; |
| | 34 | |
|
| 4 | 35 | | var temp = new int[n]; |
| | 36 | |
|
| 4 | 37 | | Array.Copy(cost, temp, n); |
| | 38 | |
|
| 22 | 39 | | for (var i = 0; i <= k; i++) |
| 7 | 40 | | { |
| 7 | 41 | | Array.Copy(cost, temp, n); |
| | 42 | |
|
| 71 | 43 | | foreach (var flight in flights) |
| 25 | 44 | | { |
| 75 | 45 | | int u = flight[0], v = flight[1], w = flight[2]; |
| | 46 | |
|
| 25 | 47 | | if (cost[u] == int.MaxValue) |
| 11 | 48 | | { |
| 11 | 49 | | continue; |
| | 50 | | } |
| | 51 | |
|
| 14 | 52 | | if (cost[u] + w < temp[v]) |
| 10 | 53 | | { |
| 10 | 54 | | temp[v] = cost[u] + w; |
| 10 | 55 | | } |
| 14 | 56 | | } |
| | 57 | |
|
| 7 | 58 | | Array.Copy(temp, cost, n); |
| 7 | 59 | | } |
| | 60 | |
|
| 4 | 61 | | return cost[dst] == int.MaxValue ? -1 : cost[dst]; |
| 4 | 62 | | } |
| | 63 | | } |