-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCheapest Flights Within K Stops
52 lines (40 loc) · 1.36 KB
/
Cheapest Flights Within K Stops
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#define pb push_back
class Solution {
void solve(vector<vector<int>>& adj,vector<vector<int>>& cost,int src,int dst,int k,int& fare,int totCost,vector<bool>& visited)
{
if(k<-1)
return;
if(src == dst)
{
fare = min(fare, totCost);
return;
}
visited[src]=true;
for(int i=0;i<adj[src].size();i++)
{
if(!visited[adj[src][i]] and (totCost + cost[src][adj[src][i]]) <= fare)
solve(adj, cost, adj[src][i], dst, k-1, fare, totCost+cost[src][adj[src][i]], visited);
}
visited[src] = false;
}
public:
int findCheapestPrice(int n, vector<vector<int>>& flights, int src, int dst, int K)
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
vector<vector<int>> adj(n);
vector<vector<int>> cost(n+1, vector<int>(n+1));
for(int i=0;i<flights.size();i++)
{
adj[flights[i][0]].pb(flights[i][1]);
cost[flights[i][0]][flights[i][1]] = flights[i][2];
}
vector<bool> visited(n+1, false);
int fare = INT_MAX;
solve(adj, cost, src, dst, K, fare, 0 ,visited);
if(fare == INT_MAX)
return -1;
return fare;
}
};