๊ด€๋ฆฌ ๋ฉ”๋‰ด

๐˜š๐˜ญ๐˜ฐ๐˜ธ ๐˜ฃ๐˜ถ๐˜ต ๐˜ด๐˜ต๐˜ฆ๐˜ข๐˜ฅ๐˜บ

[๋ฐฑ์ค€] 1260๋ฒˆ: DFS์™€ BFS - C++ ๋ณธ๋ฌธ

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์ค€๋น„/๋ฐฑ์ค€

[๋ฐฑ์ค€] 1260๋ฒˆ: DFS์™€ BFS - C++

.23 2021. 12. 21. 14:48
๋ฌธ์ œ

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

 

์ž…๋ ฅ

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

 

์ถœ๋ ฅ

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


๋ฌธ์ œ ๊ทธ๋Œ€๋กœ DFS์™€ BFS๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ํ’€๋ฉด ๋œ๋‹ค.

๐Ÿ”— DFS : https://miiinnn23.tistory.com/14

๐Ÿ”— BFS : https://miiinnn23.tistory.com/15

์ด ๋•Œ, ๋ฐฉ๋ฌธํ•  ์ˆ˜ ์žˆ๋Š” ์ •์ ์ด ์—ฌ๋Ÿฌ ๊ฐœ์ธ ๊ฒฝ์šฐ ์ •์  ๋ฒˆํ˜ธ๊ฐ€ ์ž‘์€ ๊ฒƒ ๋ถ€ํ„ฐ ๋ฐฉ๋ฌธํ•œ๋‹ค๋Š” ์กฐ๊ฑด์— ์œ ์˜ํ•œ๋‹ค.

 

์ฝ”๋“œ
#include <cstdio>
#include <queue>
#define MAX 1001

using namespace std;

int Graph[MAX][MAX] = { 0 };
bool visited[MAX] = { false };

void BFS(int vertex, int V);
void DFS(int start, int V);

int main(void) {
    int v, e, start;
    scanf("%d %d %d", &v, &e, &start);
    
    for(int i = 0; i < e; i++) {
        int a, b;
        scanf("%d %d", &a, &b);
        Graph[a][b] = Graph[b][a] = 1;
    }

    DFS(start, v);
    for(int i = 0; i <= v; i++)
        visited[i] = false;

    printf("\n");
    BFS(start, v);
    return 0;
}

void DFS(int vertex, int V) {
    visited[vertex] = true;
    printf("%d ", vertex);
    
    for(int i = 1; i <= V; i++) {
        if(visited[i] || Graph[vertex][i] == 0)
            continue;
        DFS(i, V);
    }
}

void BFS(int start, int V) {
    queue<int> q;
    q.push(start);
    visited[start] = true;

    while(!q.empty()) {
        int vertex = q.front();
        q.pop();
        printf("%d ", vertex);
        for(int i = 1; i <= V; i++) {
            if(visited[i] || Graph[vertex][i] == 0)
                continue;
            q.push(i);
            visited[i] = true;
        }
    }
    printf("\n");
}
Comments