๐ŸŽฒ 2644๋ฒˆ ์ดŒ์ˆ˜๊ณ„์‚ฐ

Jeongeunยท2023๋…„ 6์›” 26์ผ
0

๋ฐฑ์ค€

๋ชฉ๋ก ๋ณด๊ธฐ
81/187

๋ฐฑ์ค€ 2644๋ฒˆ

์ฝ”๋“œ

const fs = require('fs'); 
const input = fs.readFileSync('/dev/stdin').toString().trim().split('\n');
const num = +input.shift();
const [a, b] = input.shift().split(" ").map(Number);
const m = +input.shift();

const graph = Array.from(new Array(num + 1), () => []);

for (let i = 0; i < m; i++) {
  const [p, c] = input[i].split(" ").map(Number);
  graph[p].push(c);
  graph[c].push(p);
}

const willCheck = [a];
const checked = new Array(num + 1).fill(-1);
checked[a]++;
while (willCheck.length) {
  const check = willCheck.pop();
  for (let i = 0; i < graph[check].length; i++) {
    if (checked[graph[check][i]] === -1) {
      willCheck.push(graph[check][i]);
      checked[graph[check][i]] = checked[check] + 1;
      if (graph[check][i] === b) {
        return console.log(checked[graph[check][i]]);
      }
    }
  }
}
console.log(-1);

0๊ฐœ์˜ ๋Œ“๊ธ€