[백준 5014] 스타트링크 with node.js

waterglasses·2021년 9월 25일
0

📌 문제링크

https://www.acmicpc.net/problem/5014

📌 풀이

  • 현재 층(floor)에 U, D를 더하고 빼면서 다음 층의 이동숫자를 설정하고 btnClicks에 1씩 더하면서 계산한다.
  • floor가 TARGET_FLOOR(G)에 도달하였을 때가 최소 버튼 클릭수가 된다.

📌 코드

const fs = require('fs');
const stdin = (process.platform === 'linux' ? fs.readFileSync('/dev/stdin').toString().trim() : `100 2 1 1 0`).split(
  '\n'
);

const input = (() => {
  let line = 0;
  return () => stdin[line++];
})();

const getMinBtnClicks = () => {
  const queue = [START_FLOOR];
  const btnClicks = new Array(TOTAL_FLOOR + 1).fill(NOT_VISITED);

  btnClicks[START_FLOOR] = 0;

  while (queue.length) {
    let floor = queue.shift();

    if (floor === TARGET_FLOOR) break;

    for (let nextFloor of [floor + UP_FLOOR, floor - DOWN_FLOOR]) {
      if (nextFloor < 1 || nextFloor > TOTAL_FLOOR) continue;
      if (btnClicks[nextFloor] > -1) continue;

      queue.push(nextFloor);
      btnClicks[nextFloor] = btnClicks[floor] + 1;
    }
  }

  return btnClicks[TARGET_FLOOR];
};

const [TOTAL_FLOOR, START_FLOOR, TARGET_FLOOR, UP_FLOOR, DOWN_FLOOR] = input().split(' ').map(Number);
const NOT_VISITED = -1;

let minBtnClicks = getMinBtnClicks();
console.log(minBtnClicks === -1 ? 'use the stairs' : minBtnClicks);
profile
매 순간 성장하는 개발자가 되려고 노력하고 있습니다.

0개의 댓글