๋ฌธ์ ๋งํฌ
https://www.acmicpc.net/problem/1260
 ์ฝ๋ ์ ์ถ ๊ธฐ๋ก (๋ฉ๋ชจ๋ฆฌ ๋ฐ ์๊ฐ)
๋ฉ๋ชจ๋ฆฌ : 3656 KB
์๊ฐ : 4 ms
 Code
#include <iostream>
#include <queue>
#include <algorithm>
int N;
int M;
int V;
std::vector <int> arr[1001];
std::queue <int> bfs_arr[1001];
std::queue <int> dfs_arr[1001];
std::queue <int> bfs_result;
int visited[1001] = {0 , };
void input_faster()
{
	std::ios_base::sync_with_stdio(false);
	std::cin.tie(0);
	std::cout.tie(0);
}
void my_queue_sort(int i)
{
    sort(arr[i].begin(), arr[i].end());
    for(int j = 0 ; j<arr[i].size() ; j++){
        dfs_arr[i].push(arr[i][j]);
        bfs_arr[i].push(arr[i][j]);
    }
}
void input()
{
    int x;
    int y;
    std::cin >> N >> M >> V;
    while (M--){
        std::cin >> x >> y;
        arr[x].push_back(y);
        arr[y].push_back(x);
    }
    // queue ์ ๋ ฌ
    for(int i = 1 ; i<=N ; i++)
        my_queue_sort(i);
}
void dfs(int V)
{
    std::cout << V << " ";
    
    visited[V] = 1;
    int num = dfs_arr[V].size();
    for(int i = 0; i < num ; i++){
		int next = dfs_arr[V].front();
		if(visited[next] == 0){
			dfs(next);
		}
        dfs_arr[V].pop();
	}
}
void bfs(int V)
{
    // visited ์ด๊ธฐํ
    for (int i = 0; i < N + 1; i++) visited[i] = 0;
    bfs_result.push(V);
    visited[V] = 1;
    while(!bfs_result.empty()){
		int tmp = bfs_result.front();
		bfs_result.pop();
		std::cout << tmp << " ";
        while(!bfs_arr[tmp].empty()){
			if(visited[bfs_arr[tmp].front()] == 0){
				bfs_result.push(bfs_arr[tmp].front());
				visited[bfs_arr[tmp].front()] = 1;
			}
            bfs_arr[tmp].pop();
		}
	}
}
void print_val()
{
  dfs(V);
  std::cout << std::endl;
  bfs(V);
}
int main()
{   
	input_faster();
	input();
	print_val();
	return (0);
C++
๋ณต์ฌ
 ๋ฉ๋ชจ
๊ทธ๋ํ๋ฅผ ํ์ํ๋ ๋ฐฉ๋ฒ์๋ ํฌ๊ฒย ๊น์ด ์ฐ์  ํ์(DFS)๊ณผย ๋๋น ์ฐ์  ํ์(BFS)์ด ์์ต๋๋ค.
์ฌ๊ธฐ์ ๊ทธ๋ํ๋,ย ์ ์ (node)๊ณผ ๊ทธ ์ ์ ์ ์ฐ๊ฒฐํ๋ ๊ฐ์ (edge)์ผ๋ก ์ด๋ฃจ์ด์ง ์๋ฃ๊ตฌ์กฐ์ ์ผ์ข
์ ๋งํ๋ฉฐ,
๊ทธ๋ํ๋ฅผ ํ์ํ๋ค๋ ๊ฒ์ย ํ๋์ ์ ์ ์ผ๋ก๋ถํฐ ์์ํ์ฌ ์ฐจ๋ก๋๋ก ๋ชจ๋  ์ ์ ๋ค์ ํ ๋ฒ์ฉ ๋ฐฉ๋ฌธํ๋ ๊ฒ์ ๋งํฉ๋๋ค.
1. ์ ๋ ฅ๊ฐ ์ ์ฅ
์ฐ์ , DFS, BFS ๋ฅผ ๊ตฌํํ๊ธฐ ์ํด์๋ย ์
๋ ฅ๊ฐ์ queue ์ ์ ์ฅํ๋ ๋จ๊ณ๊ฐ ํ์ํฉ๋๋ค.
๋ง์ฝ ์๋์ ๊ฒฝ์ฐ๋ก ์
๋ ฅ๊ฐ์ด ๋ค์ด์จ๋ค๋ฉด
1 2
1 3
1 4
2 4
3 4
C++
๋ณต์ฌ
์์๋๋ก queue[a].push(b) & queue[b].push(a) ๊ณผ์ ์ ๊ฑฐ์ณ ์๋์ ๊ฐ์ queue๋ฅผ ๋ง๋ค์ ์์ต๋๋ค.
๋ฐ๋ฉด, ์๋์ ๊ฒฝ์ฐ๋ก ์
๋ ฅ๊ฐ์ด ๋ค์ด์จ๋ค๋ฉด
5 4
5 2
1 2
3 4
3 1
C++
๋ณต์ฌ
์์๋๋ก queue[a].push(b) & queue[b].push(a) ๊ณผ์ ์ ์ํํ ํย ์ ๋ ฌ์ ํด์ผ ์๋์ dfs, bfs ์๋ฆฌ๋ฅผ ์ ์ฉํ  ์ ์์ต๋๋ค.
2. DFS & BFS ์๋ฆฌ
์๋์ ๊ทธ๋ํ์์ย ํ์์ ์์ํ  ์ ์ ์ ๋ฒํธ๋ฅผ 1ย ์ด๋ผ๊ณ  ๊ฐ์ ํ๊ณ ย DFS, BFS ๋ฅผ ๊ทธ๋ฆผ์ผ๋ก ์ค๋ช
ํ๊ฒ ์ต๋๋ค.
1. ๊น์ด ์ฐ์  ํ์ (DFS, Depth-First Search):ย ์ต๋ํ ๊น์ด ๋ด๋ ค๊ฐ ๋ค, ๋์ด์ ๊น์ด ๊ฐ ๊ณณ์ด ์์ ๊ฒฝ์ฐ ์์ผ๋ก ์ด๋ย  ย ์ผ๋ฐ์ ์ผ๋ก DFS ๋ ์คํ ๋๋ ์ฌ๊ทํจ์๋ก ๊ตฌํํฉ๋๋ค.
2. ๋๋น ์ฐ์  ํ์ (BFS, Breadth-First Search): ์ต๋ํ ๋๊ฒ ์ด๋ํ ๋ค์, ๋ ์ด์ ๊ฐ ์ ์์ ๋ ์๋๋ก ์ด๋ย  ย ์ผ๋ฐ์ ์ผ๋ก BFS ๋ ํ๋ก ๊ตฌํํฉ๋๋ค
 ์ฐธ์กฐ
void input_faster()
{
	std::ios_base::sync_with_stdio(false);
	std::cin.tie(0);
	std::cout.tie(0);
}
C++
๋ณต์ฌ
๋ฅผ ์ธ ์์๋ printf, scanf ์ ๋ ์ฌ์ฉ ๊ธ์ง!





