728x90

 0. [c++] 백준  - 


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


 1. 풀이


BFS와 DFS 두가지를 모두 활용하여 풀어보았다.


 2. 소스코드


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include<iostream>
#include<vector>
#include<queue>
 
using namespace std;
 
vector<int> adj[101];
int nodeNum,virus;
//bool virus[101];
bool visited[101];
queue<int> findHere;
 
////DFS
//void DFS(int here) {
//    for (int i = 0; i < adj[here].size(); i++) {
//        int there = adj[here][i];
//        if (!visited[there]) {
//            visited[there] = true;
//            virus++;
//            findHere.push(there);
//        }
//    }
//}
 
 
//BFS
void BFS(int here) {
    for (int i = 0; i < adj[here].size(); i++) {
        int there = adj[here][i];
        if (!visited[there]) {
            visited[there] = true;
            virus++;
            BFS(there);
        }
    }
}
 
 
 
int main() {
    int N,a,b;
    cin >> nodeNum;
    cin >> N;
    for (int i = 0; i < N; i++) {
        cin >> a >> b;
        adj[a].push_back(b);
        adj[b].push_back(a);
    }
    ////DFS;
    //visited[1] = true;
    //findHere.push(1);
    //while (!findHere.empty()) {
    //    DFS(findHere.front());
    //    findHere.pop();
    //}
    //cout << virus;
 
    //BFS
    visited[1= true;
    BFS(1);
    cout << virus;
 
    return 0;
}
cs


 3. 참고





질문이나 지적 있으시면 댓글로 남겨주세요~

도움 되셨으면 하트 꾹!


+ Recent posts