백준 5567 - 결혼식 (C++)

강승구·2023년 2월 4일
0

상근이와 동기들의 관계를 그래프로 구현하여 dfs를 이용해 풀었다.
상근이와 친구, 친구의 친구까지 초대하기 때문에 dfs로 깊이가 2가 될때까지 그래프를 탐색하였고 방문한 노드를 check배열에 표시해주었다.
탐색이 끝난 뒤에 반복문을 이용해 check 배열에서 방문한 노드의 개수를 출력해주었다.

#include <iostream>
#include <vector>

using namespace std;

int n, m, from, to;
vector<int> graph[501];
bool check[501] = {false};

void dfs(int start, int depth){
    if(depth==2){
        return;
    }else{
        for(int i=0; i<graph[start].size(); i++){
            int next = graph[start][i];
            check[next] = true;
            dfs(next, depth++);
        }
    }
}

int main(){
    cin >> n >> m;
    
    int cnt = 0;
    
    for(int i=0; i<m; i++){
        cin >> from >> to;
        graph[from].push_back(to);
        graph[to].push_back(from);
    }
    check[1] = true;
    dfs(1, 0);
    
    for(int i=1; i<=n; i++){
        if(check[i]){
            cnt++;
        }
    }
    cout << cnt-1;
}
profile
강승구

0개의 댓글