[알고리즘] 2606번 바이러스

tissue·2023년 8월 1일
0

알고리즘

목록 보기
8/18
post-thumbnail

문제

난이도: 실버3
문제 유형: 그래프 탐색, 그래프 이론, 깊이 우선 탐색, 너비 우선 탐색

풀이

1부터 시작해서 노드를 방문할 때 마다 count를 증가시키면 1에서 방문하는 노드의 수를 구할 수 있다.
BFS, DFS 모두를 이용해서 풀 수 있다.

코드

#include <iostream>
#include <queue>
using namespace std;
 
int V, E; // 노드의 개수, 간선의 개수
int arr[101][101] = { 0, }; // 인접 행렬
bool visited[101] = { 0, }; // 방문 여부
int ans = 0; // 정답 count
queue<int> q;
 
void BFS(int v) {
    visited[v] = true;
    q.push(v);
    while (!q.empty()) {
        v = q.front();
        q.pop();
        for (int i = 1; i <= V; i++) {
            if (visited[i] == 0 && arr[v][i] == 1) {
                q.push(i);
                visited[i] = true;
                ans++; // 노드 방문시 카운트 증가
            }
        }
    }
}
 
int main() {
    cin >> V >> E;
    for (int i = 0; i < E; i++) {
        int a, b;
        cin >> a >> b;
        arr[a][b] = 1; // 인접 행렬 1로 초기화
        arr[b][a] = 1;
    }
 
    BFS(1); // 1번 컴퓨터부터 시작
    cout << ans;
}
profile
Better than Yesterday!

0개의 댓글