[백준 16953] A → B with node.js

waterglasses·2021년 11월 19일
0

📌 문제

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

📌 풀이

  • BFS로 풀면 쉽다.
  • 시작한는 숫자 A부터 타겟 숫자 B까지 규칙 2개에 따라 적용시키면서 queue에 추가하면 된다.

📌 코드

const fs = require('fs');
const [A, B] = (process.platform === 'linux' ? fs.readFileSync('/dev/stdin').toString().trim() : `100 40021`)
  .split(' ')
  .map(Number);

const getLeastCntOfOperation = (numOfStart, numOfTarget) => {
  const queue = [[numOfStart, 0]];

  while (queue.length) {
    const [num, cntOfOperation] = queue.shift();

    if (num === numOfTarget) return cntOfOperation + 1;

    for (let i = 0; i < 2; i++) {
      let nextNum = 0;

      if (i === 0) nextNum = 2 * num;
      else nextNum = 10 * num + 1;

      if (nextNum <= numOfTarget) {
        queue.push([nextNum, cntOfOperation + 1]);
      }
    }
  }
  return -1;
};

console.log(getLeastCntOfOperation(A, B));
profile
매 순간 성장하는 개발자가 되려고 노력하고 있습니다.

0개의 댓글