https://www.acmicpc.net/problem/13023
로직
- 재귀를 이용하여 dfs 구현
- 재귀가 5번 일어나면(deepth) 해당 관계가 존재
const solution = (N,graph)=>{
const visit = Array.from({length:N}).fill(false);
const recur = (node,deepth)=>{
if (deepth === 5) return true;
for (const next_node of graph[node]){
if (visit[next_node] === true) continue;
visit[next_node] = true;
const value = recur(next_node,deepth+1)
visit[next_node] = false;
if (value === true) return true;
}
return false;
}
for (let node=0; node<N; node++){
visit[node] = true;
if (recur(node,1)) return true;
visit[node] = false;
}
return false;
}
let graph;
let [N,M] = [null,null]
// 입력
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
rl.on('line', (line)=>{
if (N===null){
[N,M] = line.split(' ').map(Number);
graph = Array.from({length:N},()=>new Set());
} else if (M===0) {
rl.close();
} else {
M --;
const [a,b] = line.split(' ').map(Number);
graph[a].add(b)
graph[b].add(a)
}
});
rl.on('close',()=>{
const ans = solution(N,graph);
if (ans === true) console.log(1);
else console.log(0);
})
풀이 과정에서 실수
- next_node 탐색에서 const를 붙이지 않아 global.next_node에 값이 기록됨
- 이로 인해 visit을 변경하는 로직에서 false로 되돌리는 부분에 문제가 발생
'알고리즘 문제 풀이 > Javascript' 카테고리의 다른 글
[node.js] 백준 16401 과자 나눠주기 (0) | 2025.02.04 |
---|---|
[node.js] 백준 8979 올림픽 (0) | 2025.02.03 |
[node.js] 백준 1309 동물원 (1) | 2025.01.17 |
[node.js] 1347 미로만들기 (0) | 2025.01.15 |
[node.js] 16507 어두운 건 무서워 (0) | 2025.01.14 |