문제 요약
문제 설계
const input = require('fs').readFileSync('/dev/stdin').toString().trim().split('\n');
const [n, , ...arr] = input;
const visited = Array.from({ length: +n + 1 }, () => false);
const graph = Array.from({ length: +n + 1 }, () => []);
arr.forEach((item, _) => {
const [a, b] = item.split(' ').map(Number);
graph[a].push(b);
graph[b].push(a);
});
const dfs = (start) => {
let stack = [[start, 0]];
let count = 0;
visited[start] = true;
while (stack.length > 0) {
const [curNum, depth] = stack.shift();
if (depth > 2) continue;
count++;
for (const node of graph[curNum]) {
if (!visited[node]) {
visited[node] = true;
stack.push([node, depth + 1]);
}
}
}
return count - 1;
};
console.log(dfs(1));
[방문 배열 생성 및 그래프 구성]
const [n, , ...arr] = input;
const visited = Array.from({ length: +n + 1 }, () => false);
const graph = Array.from({ length: +n + 1 }, () => []);
arr.forEach((item, _) => {
const [a, b] = item.split(' ').map(Number);
graph[a].push(b);
graph[b].push(a);
});
방문 여부를 기록하는 배열(visited)을 생성하고, 그래프를 인접 그래프 형태로 만든다.
[DFS 초기화 및 탐색 과정]
const dfs = (start) => {
let stack = [[start, 0]];
let count = 0;
visited[start] = true;
while (stack.length > 0) {
const [curNum, depth] = stack.shift();
if (depth > 2) continue;
count++;
for (const node of graph[curNum]) {
if (!visited[node]) {
visited[node] = true;
stack.push([node, depth + 1]);
}
}
}
return count - 1;
};
결론 및 추가
(추천) 그래프 개념 공부할 때 도움이 되었던 글이다.
https://velog.io/@sean2337/Algorithm-DFS%EC%99%80-BFS%EC%9D%98-%EC%89%AC%EC%9A%B4-%EA%B0%9C%EB%85%90-JavaScript-%EA%B5%AC%ED%98%84-%EB%B0%A9%EB%B2%95