|  | 
|  | 1 | +/** | 
|  | 2 | + * Title: Cheapest Flights Within K Stops | 
|  | 3 | + * Description: There are n cities connected by some number of flights. You are given an array flights where flights[i] = [fromi, toi, pricei] indicates that there is a flight from city fromi to city toi with cost pricei. | 
|  | 4 | + * Author: Hasibul Islam | 
|  | 5 | + * Date: 04/05/2023 | 
|  | 6 | + */ | 
|  | 7 | + | 
|  | 8 | +/** | 
|  | 9 | + * @param {number} n | 
|  | 10 | + * @param {number[][]} flights | 
|  | 11 | + * @param {number} src | 
|  | 12 | + * @param {number} dst | 
|  | 13 | + * @param {number} k | 
|  | 14 | + * @return {number} | 
|  | 15 | + */ | 
|  | 16 | +var findCheapestPrice = function (n, flights, src, dst, k) { | 
|  | 17 | + let dMap = new Map(); | 
|  | 18 | + | 
|  | 19 | + for (let x = 0; x < flights.length; x++) { | 
|  | 20 | + const [from, to, price] = flights[x]; | 
|  | 21 | + if (dMap.has(from)) { | 
|  | 22 | + let theArray = dMap.get(from); | 
|  | 23 | + theArray[to] = price; | 
|  | 24 | + dMap.set(from, theArray); | 
|  | 25 | + } else { | 
|  | 26 | + let theArray = new Array(n).fill(-1); | 
|  | 27 | + theArray[from] = 0; | 
|  | 28 | + theArray[to] = price; | 
|  | 29 | + dMap.set(from, theArray); | 
|  | 30 | + } | 
|  | 31 | + } | 
|  | 32 | + // Map structure = < nodeIndex, [cost price to directly connect to other node] | 
|  | 33 | + | 
|  | 34 | + //return -1 if there's src node has to edge to other node | 
|  | 35 | + if (!dMap.has(src)) return -1; | 
|  | 36 | + | 
|  | 37 | + //BFS on src path | 
|  | 38 | + let theQ = [[dMap.get(src), 0]]; | 
|  | 39 | + let numOfStop = 0; | 
|  | 40 | + const dist = new Array(n).fill(Infinity); | 
|  | 41 | + let temp = []; | 
|  | 42 | + while (numOfStop <= k && theQ.length > 0) { | 
|  | 43 | + temp = []; | 
|  | 44 | + for (let y = 0; y < theQ.length; y++) { | 
|  | 45 | + const [city, cost] = theQ[y]; | 
|  | 46 | + | 
|  | 47 | + for (let x = 0; x < city.length; x++) { | 
|  | 48 | + if (city[x] !== 0 && city[x] !== -1) { | 
|  | 49 | + if (city[x] + cost >= dist[x]) continue; | 
|  | 50 | + | 
|  | 51 | + dist[x] = cost + city[x]; | 
|  | 52 | + if (dMap.has(x)) { | 
|  | 53 | + temp.push([dMap.get(x), cost + city[x]]); | 
|  | 54 | + } | 
|  | 55 | + } | 
|  | 56 | + } | 
|  | 57 | + } | 
|  | 58 | + | 
|  | 59 | + numOfStop++; | 
|  | 60 | + theQ = temp; | 
|  | 61 | + } | 
|  | 62 | + return dist[dst] !== Infinity ? dist[dst] : -1; | 
|  | 63 | +}; | 
0 commit comments