πŸ‹ 문제링크


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);

πŸ₯ λ©”λͺ¨


κ·Έλž˜ν”„λ₯Ό νƒμƒ‰ν•˜λŠ” λ°©λ²•μ—λŠ” 크게 **깊이 μš°μ„  탐색(DFS)**κ³ΌΒ **λ„ˆλΉ„ μš°μ„  탐색(BFS)**이 μžˆμŠ΅λ‹ˆλ‹€.

μ—¬κΈ°μ„œ κ·Έλž˜ν”„λž€, 정점(node)κ³Ό κ·Έ 정점을 μ—°κ²°ν•˜λŠ” κ°„μ„ (edge)으둜 이루어진 자료ꡬ쑰의 일쒅을 λ§ν•˜λ©°,

κ·Έλž˜ν”„λ₯Ό νƒμƒ‰ν•œλ‹€λŠ” κ²ƒμ€Β ν•˜λ‚˜μ˜ μ •μ μœΌλ‘œλΆ€ν„° μ‹œμž‘ν•˜μ—¬ μ°¨λ‘€λŒ€λ‘œ λͺ¨λ“  정점듀을 ν•œ λ²ˆμ”© λ°©λ¬Έν•˜λŠ” 것을 λ§ν•©λ‹ˆλ‹€.

1. μž…λ ₯κ°’ μ €μž₯

μš°μ„ , DFS, BFS λ₯Ό κ΅¬ν˜„ν•˜κΈ° μœ„ν•΄μ„œλŠ”Β μž…λ ₯값을 queue 에 μ €μž₯ν•˜λŠ” 단계가 ν•„μš”ν•©λ‹ˆλ‹€.

λ§Œμ•½ μ•„λž˜μ˜ 경우둜 μž…λ ₯값이 λ“€μ–΄μ˜¨λ‹€λ©΄

1 2
1 3
1 4
2 4
3 4