-
Notifications
You must be signed in to change notification settings - Fork 0
/
Cheapest Flights Within K Stops
34 lines (32 loc) · 1.04 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
class Solution {
public:
int findCheapestPrice(int n, vector<vector<int>>& flights, int src, int dst, int k) {
vector< pair<int,int> > adj[n];
int m=flights.size();
for(int i=0;i<m;i++){
adj[flights[i][0]].push_back({flights[i][1],flights[i][2]});
}
vector<int>dist(n,1e9);
dist[src]=0;
queue< pair<int, pair<int,int> > > q;
q.push({0,{src,0}});// stops, src, distance;
while(!q.empty()){
auto it = q.front();
q.pop();
int node= it.second.first;
int stops= it.first;
int distance= it.second.second;
if(stops> k)continue;
for(auto &itr : adj[node]){
if(distance + itr.second < dist[itr.first]){
dist[itr.first]=distance + itr.second;
q.push({stops+1,{itr.first,dist[itr.first]}});
}
}
}
if(dist[dst]==1e9)return -1;
return dist[dst];
}
};
TC: O(No. of eedges)
SC: O(no of verices)