알고리즘
DFS 문제풀이
kwonpinky
2023. 6. 8. 01:00
728x90
https://www.acmicpc.net/problem/2606
2606번: 바이러스
첫째 줄에는 컴퓨터의 수가 주어진다. 컴퓨터의 수는 100 이하이고 각 컴퓨터에는 1번 부터 차례대로 번호가 매겨진다. 둘째 줄에는 네트워크 상에서 직접 연결되어 있는 컴퓨터 쌍의 수가 주어
www.acmicpc.net
[나의 코드]
let fs=require("fs");
let input = fs.readFileSync("/dev/stdin").toString().split("\n")
let n=Number(input[0])
let m=Number(input[1])
let test= Array.from({length:n+1}).map((currentElement,i)=>[i.toString()])
for(let i=2;i<=m+1;i++){
const [a,b]=input[i].split(" ").map(Number)
if(!test[a].includes(b)){
test[a].push(b)
}
if(!test[b].includes(a)){
test[b].push(a)
}
}
let graph=test.map((item)=>item.slice(1))
let answer=0;
function DFS(graph, v, visited){
visited[v]=true
answer++
for(let x of graph[v]){
if(!visited[x]){
DFS(graph,x,visited)
}
}
}
let visited = Array(n+1).fill(false)
DFS(graph, 1,visited)
console.log(answer-1)
[정답코드]
728x90