알고리즘/알고리즘 문제 풀이

(C++) 백준 1260번 - DFS와 BFS

용꿀 2023. 6. 19. 00:21

문제 링크 : https://www.acmicpc.net/problem/1260

 

1260번: DFS와 BFS

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

www.acmicpc.net

풀이

그래프에서의 DFS와 BFS를 구현하는 문제이다.

DFS는 Stack을, BFS는 Queue를 사용해서 풀력 형식에 맞게 그래프의 정점을 하나씩 순회하도록 구현하면 된다.

#include <iostream>
#include <queue>
#include <stack>
#include <algorithm>

using namespace std;

vector<int> gp[1002];
int visited[1002];
queue<int> q;
stack<int> s;
int n, m, v, x, y;

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);

    cin >> n >> m >> v;
    while(m--){
        cin >> x >> y;
        gp[x].push_back(y);
        gp[y].push_back(x);
    }

    for(int i = 1; i <= n; i++) {
        sort(gp[i].begin(), gp[i].end());
        reverse(gp[i].begin(), gp[i].end());
    }

    s.push(v);
    while(!s.empty()){
        int pre = s.top();
        s.pop();
        if(visited[pre]) continue;
        visited[pre] = 1;
        cout << pre << " ";
        for(auto k : gp[pre]){
            if(visited[k]) continue;
            s.push(k);
        }
    }
    cout << "\n";

    for(int i = 1; i <= n; i++) {
        sort(gp[i].begin(), gp[i].end());
    }

    fill_n(visited, 1002, 0);
    q.push(v);
    while(!q.empty()){
        int pre = q.front();
        q.pop();
        if(visited[pre]) continue;
        visited[pre] = 1;
        cout << pre << " ";
        for(auto k : gp[pre]){
            if(visited[k]) continue;
            q.push(k);
        }
    }
}