본문 바로가기

Algorithm

(C++) - 백준(BOJ) 2606번 : 바이러스 답

반응형

BFS 문제 입니다.

#include <iostream>
#include <queue>
#include <vector>
#include <algorithm>
using namespace std;
int n, m, u, v, c[101],cnt;
vector <int> a[101];
queue <int> q;
void BFS(int x)
{
    q.push(x);
    c[x] = 1;
    while (!q.empty())
    {
        int x = q.front();
        q.pop();
        for (int i = 0; i < a[x].size(); i++)
        {
            int y = a[x][i];
            if (c[y] == 0)
            {
                q.push(y);
                c[y] = 1;
                cnt++;//체크가 안되었을 때 바이러스에 감염된 컴퓨터의 수를 구함
            }
        }
    }
}
int main() {
    cin >> n;//컴퓨터의 수
    cin >> m;//연결된 간선 수
    while (m--)
    {
        cin >> u >> v;
        a[u].push_back(v);
        a[v].push_back(u);
    }
    BFS(1);
    cout << cnt;
}