백준 2606번 JavaScript

yj j·2024년 1월 25일

백준2606번 node.js

const fs = require("fs");
const input = fs.readFileSync("/dev/stdin").toString().trim().split("\n");

const com = Number(input[0]);
const edge = Number(input[1]);
const graph = [];

for (let i = 1; i <= com; i += 1) graph[i] = [];
for (let i = 2; i <= edge + 1; i += 1) {
  const [x, y] = input[i].split(" ").map(Number);
  graph[x].push(y);
  graph[y].push(x);
}

let visited = new Array(com + 1).fill(false);

let count = 0;

const dfs = (v) => {
  visited[v] = true;
  count += 1;
  for (i of graph[v]) {
    if (!visited[i]) {
      dfs(i);
    }
  }
};
dfs(1);
console.log(count - 1);

그래프를 인접 리스트로 표현할 때, 인덱스 0은 사용하지 않도록 하면 직관적입니다.

profile
꿈꾸는 사람

0개의 댓글