티스토리 뷰

https://www.acmicpc.net/problem/2606

 

2606번: 바이러스

첫째 줄에는 컴퓨터의 수가 주어진다. 컴퓨터의 수는 100 이하이고 각 컴퓨터에는 1번 부터 차례대로 번호가 매겨진다. 둘째 줄에는 네트워크 상에서 직접 연결되어 있는 컴퓨터 쌍의 수가 주어

www.acmicpc.net

const fs = require('fs');
const [c,_, ...arr] = fs.readFileSync("./dev/stdin").toString().trim().split("\n");
const C = +c;
const network = arr.map(v=>v.split(' ').map(w=>+w));



class Graph{
  constructor(v){
    this.vertices = v;
    this.edge = 0; 
    this.edgeTo = [];
    this.adj = [];
    this.marked = [];
    this.route=[];
    for(let i =0; i<=this.vertices; i++){
      this.marked[i] = false; 
      this.adj[i] = [];
    }
  }

  addEdge(v,w){
    this.adj[v].push(w);
    this.adj[w].push(v);
    this.edge++;
  }

  dfs(v){
    this.marked[v] = true;
    this.route.push(v)
    this.adj[v].forEach(w=>{
      if(!this.marked[w]){
        this.dfs(w);
      }
    })
  }

  bfs(s){
    let q = [];
    this.marked[s] = true;
    q.push(s);
    while(q.length>0){
      let v =q.shift();
      this.route.push(v);
      this.adj[v].forEach(w=>{
        if(!this.marked[w]){
          this.edgeTo[w]=v;
          this.marked[w]=true;
          q.push(w)
        }
      })
    } 
  }
}




let graph = new Graph(C);
network.forEach(v=>{
  graph.addEdge(v[0],v[1])
})

graph.bfs(1);
const answer = graph.route.length-1
console.log(answer);
728x90
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
글 보관함