dijistra || method to avoid TLE || Simple

#define tiii tuple<int, int, int>
class Solution {
public:
int findCheapestPrice(int n, vector<vector>& flights, int src, int dst, int k) {

    vector<vector<pair<int, int>>> graph(n);
    
    for(auto &i : flights){
        graph[i[0]].push_back({i[1], i[2]});
    }
    
    priority_queue<tiii , vector<tiii>, greater<tiii>> pq;
    
    vector<int> dist(n+1, INT_MAX); // to avoid tle
    pq.push(make_tuple(0,src,0));  // cost, src, stops taken
    
    while(!pq.empty()){
        auto [cost, u,stops] = pq.top();
        pq.pop();
        
        if(dist[u] < stops){   // to avoid tle
            continue;
        }
        
        dist[u] = stops;   // to avoid tle
        
        if(u == dst){
            return cost;
        }
        
        if(stops > k){
            continue;
        }
        
        for(auto &child : graph[u]){
            auto [v,w] = child;
            
            pq.push(make_tuple(cost + w, v, stops+1));
        }
    }
    
    return -1;
}

};

***** #plz upvote if u like the soln*****

Comments (0)