๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿƒ algorithm/leetcode

LeetCode 787 - Cheapest Flights Within K Stops (Medium)

by HandHand 2021. 3. 2.

๋ฌธ์ œ

LeetCode - 787๋ฒˆ

ํ’€์ด ๊ณผ์ •

์ตœ๋Œ€ K ๊ฐœ์˜ ๊ฒฝ์œ ์ง€๋ฅผ ํฌํ•จํ•œ๋‹ค๋Š” ์กฐ๊ฑด ์•„๋ž˜์—์„œ ํ•œ ์ •์ ์—์„œ ๋ชฉํ‘œ ์ •์ ๊นŒ์ง€์˜ ์ตœ๋‹จ ๊ฒฝ๋กœ๋ฅผ ๊ตฌํ•˜๋Š” ๋ฌธ์ œ์ž…๋‹ˆ๋‹ค.

๋”ฐ๋ผ์„œ ๋‹จ์ผ ์ •์  - ๋ชจ๋“  ์Œ ์ตœ๋‹จ ๊ฒฝ๋กœ ์•Œ๊ณ ๋ฆฌ์ฆ˜์ธ ๋‹ค์ต์ŠคํŠธ๋ผ ์•Œ๊ณ ๋ฆฌ์ฆ˜ ์„ ๋ณ€ํ˜•ํ•ด์„œ ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•˜์˜€์Šต๋‹ˆ๋‹ค.

์‚ฌ์‹ค ๊ฐ„์„  ์„ ํƒ์„ ์œ„ํ•ด ์šฐ์„ ์ˆœ์œ„ ํ ๋„ ์‚ฌ์šฉํ•˜์ง€ ์•Š์•„์„œ ์• ๋งคํ•œ ๋ถ€๋ถ„์ด ์žˆ์ง€๋งŒ
BFS + Dijkstra ์˜ ์œ ํ˜•์ด๋ผ๊ณ  ์ƒ๊ฐํ•˜๋ฉด ๋  ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.

์ด ๋ฌธ์ œ์˜ ํ•ต์‹ฌ์€ k ๊ฐœ์˜ ๊ฒฝ์œ ์ง€๋ฅผ ์–ด๋–ป๊ฒŒ ์ฒ˜๋ฆฌํ•  ๊ฒƒ์ธ๊ฐ€ ์ž…๋‹ˆ๋‹ค.

๊ธฐ์กด์˜ ๋‹ค์ต์ŠคํŠธ๋ผ ์•Œ๊ณ ๋ฆฌ์ฆ˜ ์€ ์ด์ „์— ๋ฐœ๊ฒฌ๋˜์–ด ํ์— ์ €์žฅ๋˜์–ด ์žˆ๋Š” ๊ฒฝ๋กœ ์ค‘
๋” ์งง์€ ๊ฒฝ๋กœ๊ฐ€ ๋ฐœ๊ฒฌ๋˜์–ด dist ๊ฐ€ ๊ฐฑ์‹  ๋˜์—ˆ์„ ๊ฒฝ์šฐ ํ์—์„œ ์ด์ „์— ๋ฐœ๊ฒฌ๋œ ๊ฒฝ๋กœ๊ฐ€ pop ๋˜์–ด
์ฒ˜๋ฆฌํ•  ์ฐจ๋ก€๊ฐ€ ๋˜๋ฉด ๊ทธ๋ƒฅ ๋ฌด์‹œ๋ฅผ ํ•ด์ฃผ๋Š” ๋ฐฉ์‹์œผ๋กœ ์ฒ˜๋ฆฌ๋ฅผ ํ•ด์คฌ์Šต๋‹ˆ๋‹ค.

ํ•˜์ง€๋งŒ ์ด๋ฒˆ ๋ฌธ์ œ์—์„œ๋Š” ๋น„๋ก ๋น„์šฉ์ด ๋” ๋“ค๋”๋ผ๋„ ๋ฌด์‹œํ•˜์ง€ ๋ง๊ณ  ํ•ด๋‹น ๊ฒฝ๋กœ๋ฅผ ํ†ตํ•ด
์ตœ๋Œ€ k ๊ฐœ์˜ ์ •์ ์œผ๋กœ ๋ฐฉ๋ฌธ ๊ฐ€๋Šฅํ•œ ๋ชจ๋“  ์ง€์ ์„ ํŒŒ์•…ํ•ด์ค˜์•ผํ•ฉ๋‹ˆ๋‹ค.

์˜ˆ๋ฅผ ๋“ค์–ด k = 1 ์ผ๋•Œ ์œ„์™€ ๊ฐ™์ด ์ƒ๊ฐ„ ๊ทธ๋ž˜ํ”„์—์„œ 0 -> 1 -> 2 ๋กœ ๊ฐ€๋Š” ๊ฒฝ๋กœ ๊ฐ’์€ 2 ๋ผ๋Š” ์‚ฌ์‹ค์„ ์•Œ๊ฒŒ ๋˜์—ˆ๋‹ค๊ณ  ํ•ด์„œ
0 -> 2 ๋กœ ๊ฐ€๋Š” ๊ฒฝ๋กœ๋ฅผ ๋ฌด์‹œํ•˜๊ฒŒ ๋˜๋ฉด 0 -> 2 -> 3 ์œผ๋กœ ๊ฐ€๋Š” ๊ฒฝ๋กœ๋ฅผ ์ฐพ์ง€ ๋ชปํ•˜๊ฒŒ ๋ฉ๋‹ˆ๋‹ค.

์ฝ”๋“œ

/**
 * @param {number} n
 * @param {number[][]} flights
 * @param {number} src
 * @param {number} dst
 * @param {number} K
 * @return {number}
 */
var findCheapestPrice = function (n, flights, src, dst, K) {
  // ์ธ์ ‘ ๋ฆฌ์ŠคํŠธ ์ƒ์„ฑ
  const adj = new Map();
  for (let [frm, to, weight] of flights) {
    if (adj.has(frm)) adj.get(frm).push([to, weight]);
    else adj.set(frm, [[to, weight]]);
  }

  function dijkstra(start) {
    let q = [];
    let dist = new Array(n).fill(Infinity);

    q.push([start, 0, 0]);
    dist[start] = 0;

    while (q.length) {
      let [here, cost, move] = q.shift();

      if (move > K || !adj.get(here)) continue;

      for (let [there, weight] of adj.get(here)) {
        let nextDist = cost + weight;
        if (dist[there] > nextDist) {
          dist[there] = nextDist;
          q.push([there, nextDist, move + 1]);
        }
      }
    }

    return dist[dst];
  }

  let ans = dijkstra(src);
  return ans === Infinity ? -1 : ans;
};
๋ฐ˜์‘ํ˜•

๐Ÿ’ฌ ๋Œ“๊ธ€