[백준 17204] 죽음의 게임 with node.js

waterglasses·2021년 11월 15일
0

📌 문제

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

📌 풀이

  • 더게임오브데스라는 게임에서 영기(0)부터 보성(K)까지 이어져 있는 길이를 구하면 된다.
  • 이어져있지 않으면 -1을 출력한다.

📌 코드

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

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

const getLeastDistances = (startVertex) => {
  const visitedVertices = new Array(N).fill(false);
  const queue = [startVertex];
  let distance = 0;

  while (queue.length) {
    const vertex = queue.shift();

    if (vertex === K) return distance;

    for (let nextVertex of graph[vertex]) {
      if (visitedVertices[nextVertex]) continue;
      visitedVertices[nextVertex] = true;
      queue.push(nextVertex);
      distance += 1;
    }
  }

  return -1;
};

const [N, K] = input().split(' ').map(Number);
const graph = Array.from(new Array(N), () => new Array());
for (let i = 0; i < N; i++) {
  const vertex = Number(input());
  graph[i].push(vertex);
}

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

0개의 댓글