2606번: 바이러스(13분)

myeongrangcoding·2023년 12월 6일
0

백준

목록 보기
17/47

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

구현 아이디어 2분 구현 11분

풀이(DFS)

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;
vector<int> VecGraph[101];
int Sum{};
int Check[101];

int DFS(int Vertex)
{
    int Num = 1;
    Check[Vertex] = 1;
    if (VecGraph[Vertex].size() == 0)
    {
        return Num;
    }

    for (int i = 0; i < VecGraph[Vertex].size(); ++i)
    {
        if (Check[VecGraph[Vertex][i]]) continue;
        Num += DFS(VecGraph[Vertex][i]);
    }

    return Num;
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    //freopen("input.txt", "rt", stdin);

    int N{}, M{};
    cin >> N >> M;

    int Computer1{}, Computer2{};
    for (int i = 0; i < M; ++i)
    {
        cin >> Computer1 >> Computer2;

        VecGraph[Computer1].push_back(Computer2);
        VecGraph[Computer2].push_back(Computer1);
    }

    Sum = DFS(1);
	
    // 1번 컴퓨터는 제외한다.
    cout << Sum - 1;

    return 0;
}

풀이(BFS)

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>

using namespace std;
vector<int> VecGraph[101];
int Sum{};
int Check[101];
queue<int> Q;

void BFS()
{
    while (!Q.empty())
    {
        int CurrentVertex = Q.front();
        Q.pop();

        for (int i = 0; i < VecGraph[CurrentVertex].size(); ++i)
        {
            if (Check[VecGraph[CurrentVertex][i]]) continue;
            Q.push(VecGraph[CurrentVertex][i]);
            Check[VecGraph[CurrentVertex][i]] = 1;
            ++Sum;
        }
    }
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    //freopen("input.txt", "rt", stdin);

    int N{}, M{};
    cin >> N >> M;

    int Computer1{}, Computer2{};
    for (int i = 0; i < M; ++i)
    {
        cin >> Computer1 >> Computer2;

        VecGraph[Computer1].push_back(Computer2);
        VecGraph[Computer2].push_back(Computer1);
    }

    Q.push(1);
    Check[1] = 1;

    BFS();

    cout << Sum;

    return 0;
}
profile
명랑코딩!

0개의 댓글