[C++] 백준 2606번 바이러스

xyzw·2025년 2월 18일
0

algorithm

목록 보기
31/61

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

풀이

DFS를 이용해서 풀었다. 1번 컴퓨터를 시작으로 DFS를 실행하고, 1번을 제외하여 탐색된 컴퓨터의 수를 출력하였다.

#include <iostream>
using namespace std;

int n;
int ans;
bool graph[101][101];
bool visited[101];

void DFS(int start) {
    visited[start] = true;
    ans++;
    for(int i=1; i<=n; i++) {
        if(graph[start][i] && !visited[i]) {
            DFS(i);
        }
    }
    return;
}

int main()
{
    int m, a, b;
    cin >> n >> m;
    
    while(m--) {
        cin >> a >> b;
        graph[a][b] = graph[b][a] = true;
    }
    
    DFS(1);
    
    cout << ans-1;
    
    return 0;
}

0개의 댓글