Baekjoon Review

[Silver 2] 1260번 DFS와 BFS

hanseongbugi 2023. 10. 24. 16:26

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의 탐색 결과를 출력하면 된다.

 

#include <iostream>
#include <vector>
#include <queue>
#include<algorithm>
using namespace std;

int graph[1001][1001] = {0, };
int N, M, V;
int visited[1001] = {0,};
vector<int> stack;
queue<int> q;

void DFS(){
    stack.push_back(V);
    
    while(!stack.empty()){
        int p = stack.back();
        stack.pop_back();
        
        if(visited[p]) continue;
        
        visited[p] = 1;
        cout<<p<<' ';
        for(int next = N; next >= 1; next--){
        	if(!visited[next] && graph[p][next])
            	stack.push_back(next);
        }
    }
    cout<<'\n';
}

void init(){
    for(int i = 0;i<1001;i++){
        visited[i] = 0;
    }
}

void BFS(){
    q.push(V);

	 while(!q.empty()){
        int p = q.front();
        q.pop();
        
        if(visited[p]) continue;
        
        visited[p] = 1;
        cout<<p<<' ';
        for(int next = 1; next <= N; next++){
        	if(!visited[next] && graph[p][next])
            	q.push(next);
        }
    }
    cout<<'\n';
}

int main(){
    ios::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    
    cin>>N>>M>>V;
    for(int i = 0;i<M;i++){
        int p, e;
        cin>>p>>e;
        graph[p][e] = 1;
        graph[e][p] = 1;
    }
    DFS();
    init();
    BFS();
    
}

 

BFS와 DFS의 자세한 설명은 아래를 참고하면 된다.

https://hanseongbugi2study.tistory.com/37

 

<algorithm> 깊이 우선 탐색(DFS)

- DFS란, 그래프 전체를 탐색하는 하나의 방법으로써, 하나의 가지(branch)를 모두 탐색한 이후에 다음 branch로 이동하는 방법이다. - 시작 노드에서 깊이가 커지는 방향으로 탐색을 진행하여 더 이

hanseongbugi2study.tistory.com

https://hanseongbugi2study.tistory.com/36

 

<algorithm> 너비 우선 탐색(BFS)

너비 우선 탐색(BFS, Breadth-First Search) - 시작 정점으로부터 가까운 정점을 먼저 방문하고 멀리 떨어져 있는 정점을 나중에 방문하는 순회 방법 - 큐를 사용하여 구현됨 A 노드(시작 노드)를 방문한

hanseongbugi2study.tistory.com