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

문제 설명

1번 노드와 연결되어 있는 노드가 몇 개인지 세면 된다.

문제 접근

단순한 그래프 순회 문제이므로 BFS를 이용한다.

1번 노드와 연결된 노드의 개수만 세면 되므로, BFS는 1번 노드를 출발점으로 한 번만 돌아도 된다.

 

전체 코드

#include <iostream>
#include <vector>
#include <queue>

using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);

    int numOfCom, numOfPair;
    cin >> numOfCom >> numOfPair;
    vector<int> g[numOfCom + 1];  //인접 리스트
    vector<bool> visited(101, false);   //방문 배열
    queue<int> q;
    int count = 0;


    //인접리스트 채우기
    for (int i = 0; i < numOfPair; i++)
    {
        int a, b;
        cin >> a >> b;
        g[a].push_back(b);
        g[b].push_back(a);
    }

    //1번째 정점은 방문
    visited[1] = true;
    q.push(1);

    //1번부터 BFS를 한 번 돌면 연결된 정점의 개수를 알 수 있음
    while(!q.empty())
    {
        int x = q.front();
        q.pop();
        for (int i = 0; i < g[x].size(); i++) {
            if (!visited[g[x][i]])
            {
                visited[g[x][i]] = true;
                q.push(g[x][i]);
                count++;
            }
        }
    }
    cout << count << "\n";
    return 0;
}