문제 출처 : https://www.acmicpc.net/problem/11724

<C++코드, Bfs>

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
#include<iostream>
#include<vector>
#include<queue>
using namespace std;
vector<int> a[1001];
bool v[1001];
int n,m;
void bfs(int start)
{
    queue<int> q;
    v[start]=true;
    q.push(start);
    while(!q.empty())
    {
        int x=q.front();
        q.pop();
        for(int i=0;i<a[x].size();i++)
        {
            int y=a[x][i];
            if(!v[y])
            {
                v[y]=true;
                q.push(y);
                
            }
        }
    }
        
    
}
int main()
{
    cin>>n>>m;
    for(int i=0;i<m;i++)
    {
        int q,w;
        cin>>q>>w;
        a[q].push_back(w);
        a[w].push_back(q);
    }
    int cnt=0;
    for(int i=1;i<=n;i++)
    {
        if(!v[i])
        {
            bfs(i);
            cnt++;
        }
    }
    cout<<cnt<<endl;
 
 
    return 0;
    
}
cs

<C++코드, Dfs>

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
#include<iostream>
#include<vector>
using namespace std;
vector<int> a[1001];
bool v[1001];
int n,m;
 
void dfs(int x)
{
    if(v[x]) return ;
    v[x]=true;
    for(int i=0;i<a[x].size();i++)
    {
        int y=a[x][i];
        if(!v[y])
        {
            dfs(y);
        }
    }
}
int main(void){
    int cnt=0;
    
    cin>>n>>m;
    for(int i=0;i<m;i++)
    {
        int q,w;
        cin>>q>>w;
        a[q].push_back(w);
        a[w].push_back(q);
    }
    for(int i=1;i<=n;i++)
    {
        if(!v[i])
        {
            dfs(i);
            cnt++;
    }
    }
    cout<<cnt<<endl;
    return 0;
    
}
cs

'백준 온라인 저지 > BFS, DFS (그래프)' 카테고리의 다른 글

1697번_숨바꼭질(Bfs)  (0) 2019.12.02
7576번_토마토 (Bfs)  (0) 2019.11.27
2667번_단지번호붙이기(Bfs)  (0) 2019.11.26
2178번_미로탐색(Bfs)  (0) 2019.11.26
7562번_나이트의 이동(Bfs)_ 아직  (0) 2019.11.26

+ Recent posts