๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

๐Ÿ“ ์•Œ๊ณ ๋ฆฌ์ฆ˜/BOJ

[C++/๋ฐฑ์ค€] 1260 : DFS์™€ BFS

728x90

๋ฌธ์ œ

๊ทธ๋ž˜ํ”„๋ฅผ DFS๋กœ ํƒ์ƒ‰ํ•œ ๊ฒฐ๊ณผ์™€ BFS๋กœ ํƒ์ƒ‰ํ•œ ๊ฒฐ๊ณผ๋ฅผ ์ถœ๋ ฅํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์‹œ์˜ค. ๋‹จ, ๋ฐฉ๋ฌธํ•  ์ˆ˜ ์žˆ๋Š” ์ •์ ์ด ์—ฌ๋Ÿฌ ๊ฐœ์ธ ๊ฒฝ์šฐ์—๋Š” ์ •์  ๋ฒˆํ˜ธ๊ฐ€ ์ž‘์€ ๊ฒƒ์„ ๋จผ์ € ๋ฐฉ๋ฌธํ•˜๊ณ , ๋” ์ด์ƒ ๋ฐฉ๋ฌธํ•  ์ˆ˜ ์žˆ๋Š” ์ ์ด ์—†๋Š” ๊ฒฝ์šฐ ์ข…๋ฃŒํ•œ๋‹ค. ์ •์  ๋ฒˆํ˜ธ๋Š” 1๋ฒˆ๋ถ€ํ„ฐ N๋ฒˆ๊นŒ์ง€์ด๋‹ค.

์ž…๋ ฅ

์ฒซ์งธ ์ค„์— ์ •์ ์˜ ๊ฐœ์ˆ˜ N(1 ≤ N ≤ 1,000), ๊ฐ„์„ ์˜ ๊ฐœ์ˆ˜ M(1 ≤ M ≤ 10,000), ํƒ์ƒ‰์„ ์‹œ์ž‘ํ•  ์ •์ ์˜ ๋ฒˆํ˜ธ V๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ๋‹ค์Œ M๊ฐœ์˜ ์ค„์—๋Š” ๊ฐ„์„ ์ด ์—ฐ๊ฒฐํ•˜๋Š” ๋‘ ์ •์ ์˜ ๋ฒˆํ˜ธ๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ์–ด๋–ค ๋‘ ์ •์  ์‚ฌ์ด์— ์—ฌ๋Ÿฌ ๊ฐœ์˜ ๊ฐ„์„ ์ด ์žˆ์„ ์ˆ˜ ์žˆ๋‹ค. ์ž…๋ ฅ์œผ๋กœ ์ฃผ์–ด์ง€๋Š” ๊ฐ„์„ ์€ ์–‘๋ฐฉํ–ฅ์ด๋‹ค.

์ถœ๋ ฅ

์ฒซ์งธ ์ค„์— DFS๋ฅผ ์ˆ˜ํ–‰ํ•œ ๊ฒฐ๊ณผ๋ฅผ, ๊ทธ ๋‹ค์Œ ์ค„์—๋Š” BFS๋ฅผ ์ˆ˜ํ–‰ํ•œ ๊ฒฐ๊ณผ๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค. V๋ถ€ํ„ฐ ๋ฐฉ๋ฌธ๋œ ์ ์„ ์ˆœ์„œ๋Œ€๋กœ ์ถœ๋ ฅํ•˜๋ฉด ๋œ๋‹ค.

 


 

๋ฐฑ์ค€ ์‹ค๋ฒ„2 / dfs์™€ bfs

 

๋Š˜ ๊ฐœ๋…์€ ์•Œ๊ณ  ์žˆ์—ˆ์ง€๋งŒ, ๊ฐ์žก๊ณ  ์ œ๋Œ€๋กœ ๋ฌธ์ œ ํ’€์–ด๋ณธ๊ฑด ์ฒ˜์Œ์ธ๋“ฏ

๋†€๋ž๊ฒŒ๋„ 1์‹œ๊ฐ„๋™์•ˆ ์‚ฝ์งˆํ•จ..^^  (์š•ํ•˜์ง€๋งˆ์„ธ์š” ์‘์• )

 

๊ทธ๋ž˜๋„ ์‚ฝ์งˆํ•œ ๋งŒํผ ๋‡Œ์— ์ œ๋Œ€๋กœ ๋ฐ•ํ˜”๋‹ค.

์ด์ œ ๋‹ค๋ฅธ ๊ทธ๋ž˜ํ”„ ๋ฌธ์ œ๋“ค์€ ์‰ฝ๊ฒŒ ํ’€ ์ˆ˜ ์žˆ์„๊ฑฐ์•ผ ๊ณผ์—ฐ

 

๊ธฐ์–ตํ•ด๋‘ฌ๋ผ ๋ฏธ๋ž˜์˜ ๋ฉ์ฒญํ•œ ๋‚˜์•ผ

1. bfs๋Š” ๋ฌด์กฐ๊ฑด queue ์“ฐ๋Š”๊ฒŒ ์ •์„์ž„ ๊ผผ์ˆ˜ใ„ดใ„ด
2. dfs ์žฌ๊ท€๋กœ ํ’€๊ฑฐ๋ฉด ์ „์—ญ๋ณ€์ˆ˜ ํ•„์ˆ˜.
3. ๊ทธ๋ž˜ํ”„ ๋ฌธ์ œ๋Š” ์ž…๋ ฅ๋ฐ›์ž๋งˆ์ž matrix๋กœ ์ €์žฅํ•ด๋†“์œผ๋ฉด ๋‚˜์ค‘์— ํŽธํ•˜๋‹ค

 

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

int n;
int m;
int v;
int mat[1001][1001];

int dfs_visited[1002] = {0}; // dfs๋Š” ์žฌ๊ท€๋กœ ํ’€๊ฑฐ๋ผ์„œ ์ „์—ญ๋ณ€์ˆ˜ ๋ฐฐ์—ด visited ํ•„์š”

int dfs(int V){
    cout << V << " ";
    dfs_visited[V] = 1;
    for (int i = 1; i <= n; ++i){
        if(dfs_visited[i]==1 || mat[V][i] == 0) continue; // ์ด๋ฏธ ๋ฐฉ๋ฌธํ–ˆ๊ฑฐ๋‚˜ mat์— ์—†๋‹ค๋ฉด ์Šคํ‚ต
        // V = i
        dfs(i);
    }
    return 0;
}

int bfs(int V){
    int bfs_visited[1002] = {0};
    queue<int> q; // bfs๋Š” ํ•ญ์ƒ queue๋ฅผ ์‚ฌ์šฉํ•œ๋‹ค.
    q.push(V);
    bfs_visited[V] = 1;
    while(!q.empty()){
        int x = q.front();
        cout << x << " ";
        q.pop();
        for (int i = 1; i <= n; ++i){
            if(bfs_visited[i]==1 || mat[x][i] == 0) continue; // ์ด๋ฏธ ๋ฐฉ๋ฌธํ–ˆ๊ฑฐ๋‚˜ mat์— ์—†๋‹ค๋ฉด ์Šคํ‚ต
            q.push(i);
            bfs_visited[i] = 1;
        }
    }
    return 0;
}

int main(){
    
    cin >> n >> m >> v;
    int x, y;
    for (int i = 0; i < m; ++i) {
        cin >> x >> y;
        mat[x][y] = mat[y][x] = 1; // ๋งคํŠธ๋ฆญ์Šค๋กœ ๊ทธ๋ž˜ํ”„ ํ‘œํ˜„
    }
    int V = v;
    dfs(V);
    cout << "\n";
    bfs(V);
    return 0;
}

 

728x90