알고리즘/백준

[백준 1260] DFS와 BFS C++

겜도리도리 2022. 5. 31. 23:34
반응형

문제

백준 1260 DFS와 BFS (C++)

 

1260번: DFS와 BFS

첫째 줄에 정점의 개수 N(1 ≤ N ≤ 1,000), 간선의 개수 M(1 ≤ M ≤ 10,000), 탐색을 시작할 정점의 번호 V가 주어진다. 다음 M개의 줄에는 간선이 연결하는 두 정점의 번호가 주어진다. 어떤 두 정점 사

www.acmicpc.net

풀이

탐색의 가장 기본 of 기본 문제입니다.

주어진 조건에 따라 V부터 DFS 및 BFS를 실행하고, node를 출력합니다.

소스 코드

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
65
66
67
68
69
70
71
72
73
74
75
76
#include<iostream>
#include<vector>
#include<algorithm>
#include<cstring>
#include<memory.h>
#include<queue>
using namespace std;
 
int N, M, V;
bool graph[1001][1001];
bool visited[1001];
 
void BFS(int start)
{
    visited[start] = true;
    queue<int> q;
    q.push(start);
 
    while (1)
    {
        if (q.empty())
            break;
 
        int node = q.front();
        q.pop();
        cout << node << ' ';
 
        for (int i = 1; i <= N; i++)
        {
            int next = i;
            if (!visited[next] && graph[node][next])
            {
                q.push(next);
                visited[next] = true;
            }
        }
    }
    cout << '\n';
}
 
void DFS(int node)
{
    visited[node] = true;
    cout << node << ' ';
    for (int i = 1; i <= N; i++)
    {
        int next = i;
        if (!visited[next] && graph[node][next])
        {
            DFS(next);
        }
    }
}
 
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
 
    cin >> N >> M >> V;
 
    for (int i = 0; i < M; i++)
    {
        int start, end;
        cin >> start >> end;
        graph[start][end= true;
        graph[end][start] = true;
    }
 
    DFS(V);
    cout << '\n';
    memset(visited, 0sizeof(visited));
    BFS(V);
 
    return 0;
}
cs
반응형

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

[백준 2805] 나무 자르기 C++  (0) 2022.06.22
[백준 2667] 단지번호붙이기 C++  (0) 2022.06.01
[백준 15654] N과 M (5) C++  (0) 2022.05.02
[백준 13335] 트럭 C++  (0) 2022.04.30
[백준 2309] 일곱 난쟁이 C++  (0) 2022.03.30