λ³Έλ¬Έ λ°”λ‘œκ°€κΈ°
πŸƒ algorithm/leetcode

LeetCode 752 - Open the Lock (Medium)

by HandHand 2021. 3. 4.

문제

LeetCode - 752번

풀이 κ³Όμ •

λ¬Έμžμ—΄μ„ κΈ°μ€€μœΌλ‘œ νŠΉμ • μˆ«μžμ— λ„λ‹¬ν•˜κΈ° μœ„ν•œ μ΅œμ†Œ νšŒμ „μˆ˜λ₯Ό κ΅¬ν•˜λŠ” λ¬Έμ œμž…λ‹ˆλ‹€.

각 μˆ«μžμ— λŒ€ν•΄μ„œ μ¦κ°€ν•˜κ±°λ‚˜ κ°μ†Œν•  수 있으며 deadends 에 ν¬ν•¨λ˜μ§€ μ•ŠλŠ” μˆ«μžμ— λŒ€ν•΄μ„œλ§Œ 탐색을 μ§„ν–‰ν•©λ‹ˆλ‹€.
λ”°λΌμ„œ 쑰건에 λ§žλ„λ‘ BFS λ₯Ό μˆ˜ν–‰ν•˜λ©° λͺ©ν‘œ μˆ«μžμ— λ„λ‹¬ν•˜κΈ° μœ„ν•œ μ΅œμ†Œ 횟수λ₯Ό κ΅¬ν•˜λ©΄ λ©λ‹ˆλ‹€.

μ½”λ“œ

/**
 * @param {string[]} deadends
 * @param {string} target
 * @return {number}
 */
var openLock = function (deadends, target) {
  const digits = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];

  function bfs(start) {
    if (deadends.includes(start)) return -1;

    q = [];
    visit = new Array(10000).fill(false);

    q.push([start, 0]);
    visit[+start] = true;

    while (q.length) {
      const [here, cost] = q.shift();
      if (here === target) return cost;

      for (let i = 0; i < 4; i++) {
        let digit = +here[i];

        const prevDigitIdx = digit - 1 < 0 ? 9 : digit - 1;
        const nextDigitIdx = (digit + 1) % 9;

        const prevDigit = `${digits[prevDigitIdx]}`;
        const nextDigit = `${digits[nextDigitIdx]}`;

        [prevDigit, nextDigit].forEach((newDigit) => {
          const there = here.slice(0, i) + newDigit + here.slice(i + 1);
          if (!deadends.includes(there) && !visit[+there]) {
            q.push([there, cost + 1]);
            visit[+there] = true;
          }
        });
      }
    }

    return -1;
  }

  const answer = bfs("0000");
  return answer;
};
λ°˜μ‘ν˜•

πŸ’¬ λŒ“κΈ€