본문 바로가기
코테/백준

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

by gayoungeeda 2023. 7. 28.
728x90

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

 

문제 설명


문제 풀이

#include<stdio.h>
int map[101][101], chk[101];
int n, m;
void pro(int x, int y) {
    if(chk[x] == 1) return;

    chk[x] = 1;
    for(int i = 1; i <= n; i++) {
        if(map[x][i] == 1) pro(i, 1);
    }
}
int main()
{
    int i, x, y, cnt = 0;
    scanf("%d%d", &n, &m);

    for(i = 0; i < m; i++) {
        scanf("%d%d", &x, &y);
        map[x][y] = 1;
        map[y][x] = 1;
    }

    pro(1,1);

    for(i = 2; i <= n; i++) {
        if(chk[i] == 1) cnt++;
    }

    printf("%d", cnt);

    return 0;
}

 

벡터를 사용해서 푼 코드

#include<stdio.h>
#include<vector>
#include<algorithm>
using namespace std;
vector <int> map[101];
int n, s, chk[101], answer;
void dfs(int x) {
    chk[x] = 1; answer++;
    for(int i = 0; i < map[x].size(); i++) {
        if(chk[map[x][i]]) continue;
        dfs(map[x][i]);
    }
}
int main()
{
    int i, x, y;
    scanf("%d%d", &n, &s);

    for(i = 0; i < s; i++) {
        scanf("%d%d", &x, &y);
        map[x].push_back(y);
        map[y].push_back(x);
    }

    dfs(1);
    printf("%d", answer-1);

    return 0;
}

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

[백준] 1874 스택 수열 - C++  (0) 2023.07.29
[백준] 10773 제로 - C++  (0) 2023.07.29
[백준] 9461 파도반 수열 - C++  (0) 2023.07.28
[백준] 14888 연산자 끼워넣기 - C++  (0) 2023.07.27
[백준] 1912 연속합 - C++  (0) 2023.07.27