새소식

Baekjoon

[BaekJoon] 2644 번 촌수계산 문제 - (nodejs)

  • -
728x90
문제 번호 :  2644 번

문제 바로가기 https://www.acmicpc.net/problem/2644

 

<<< 문제 내용 >>>

 

const fs = require("fs"); const filePath = process.platform === "linux" ? "/dev/stdin" : "./input.txt"; let input = fs.readFileSync(filePath).toString().trim().split("\n"); const N = Number(input.shift()); let graph = Array.from(Array(N + 1), () => new Array(0)); const [a, b] = input[0].split(" ").map(Number); const graphLen = Number(input[1]); // 그래프 연결 for (let i = 2; i < 2 + graphLen; i++) { const [start, end] = input[i].split(" ").map(Number); graph[start].push(end); graph[end].push(start); } // bfs 시작 const bfs = (idx, cnt) => { let queue = [[idx, cnt]]; let visited = new Array(N + 1).fill(false); while (queue.length) { [idx, cnt] = queue.shift(); visited[idx] = true; while (graph[idx].length) { let temp = graph[idx].pop(); if (temp === b) return cnt + 1; queue.push([temp, cnt + 1]); } } return -1; }; console.log(bfs(a, 0));

 

 

도움이 되셨다면 공감 부탁드립니다.

Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.