티스토리 뷰

알고리즘/백준

백준2606[nodejs] 바이러스

민트초코수장 2021. 2. 4. 00:34
const readline = require("readline");

let input = [];
let arr = [];
let visited = [];
let infection = [];

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

rl.on("line", (line) => input.push(line.trim())).on("close", () => {
  const [computers, pairs] = [parseInt(input[0]), parseInt(input[1])];
  input.splice(0, 2);
  arr = Array.from(Array(computers + 1), () => Array(computers + 1).fill(0));
  for (let i of input) {
    let [x, y] = i.split(" ").map(Number);
    arr[x][y] = arr[y][x] = 1;
  }
  visited = new Array(computers + 1).fill(false);

  dfs(1);
  console.log(infection.length - 1);
});

const dfs = (v) => {
  visited[v] = true;
  infection.push(v);
  for (let i in arr) {
    if (arr[v][i] === 1 && !visited[i]) {
      dfs(i);
    }
  }
};

 

arr 안에 간선으로 연결되어있는 부분은 1로 바꿔주고

dfs를 이용해 vistied배열로 방문한 곳은 다시 방문하지 않게 해서

dfs로 구현하였다.

 

dfs와 bfs보단 쉬웠다

 

반응형

'알고리즘 > 백준' 카테고리의 다른 글

백준 7576 [nodejs] 토마토  (0) 2021.02.04
백준2178[nodejs] 미로 탐색  (0) 2021.02.04
백준1012[nodejs]유기농 배추  (0) 2021.02.04
백준2667[nodejs]단지번호붙이기  (0) 2021.02.04
백준1260[nodejs] DFS와 BFS  (0) 2021.02.03
Comments