[c++] ์•Œ๊ณ ๋ฆฌ์ฆ˜ ๊ฐœ๋…๊ณต๋ถ€ :: ๊ทธ๋ž˜ํ”„ ํƒ์ƒ‰ (BFS, DFS)

๊ทธ๋ž˜ํ”„

ํƒ์ƒ‰

๊ทธ๋ž˜ํ”„๋ฅผ ํƒ์ƒ‰ํ•˜๋Š” ๊ธฐ๋ฒ•์—๋Š” ๋Œ€ํ‘œ์ ์œผ๋กœ 2๊ฐ€์ง€๊ฐ€ ์žˆ๋‹ค. ๋„ˆ๋น„ ์šฐ์„  ํƒ์ƒ‰์ธ BFS(Breadth-First Search)์™€ ๊นŠ์ด ์šฐ์„  ํƒ์ƒ‰์ธ DFS(Depth-First Search)์ด๋‹ค.

 

BFS

BFS๋Š” ํ๋ฅผ ์ด์šฉํ•˜์—ฌ ๊ตฌํ˜„ํ•œ๋‹ค.

 

์„ค๋ช…

ํŠธ๋ฆฌ๋กœ ์˜ˆ๋ฅผ ๋“ค์—ˆ์ง€๋งŒ, ๋ชจ๋“  ๊ทธ๋ž˜ํ”„์—์„œ ๋งˆ์ฐฌ๊ฐ€์ง€๋กœ ๋™์ž‘ํ•œ๋‹ค.

  1. ๋ฃจํŠธ ๋…ธ๋“œ๋ฅผ queue์— ๋„ฃ๋Š”๋‹ค.

 

  1. queue์˜ ๋…ธ๋“œ๋ฅผ ํ•˜๋‚˜ ๊บผ๋‚ธ ํ›„, ํ•ด๋‹น ๋…ธ๋“œ์™€์˜ ์ธ์ ‘ ๋…ธ๋“œ๋ฅผ ๋ชจ๋‘ queue์— ๋„ฃ๋Š”๋‹ค.

  2. ์œ„์˜ ๋ฐฉ์‹์„ ๋ชจ๋“  ๋…ธ๋“œ๊ฐ€ ์™„๋ฃŒ๋  ๋•Œ๊นŒ์ง€ ๋ฐ˜๋ณตํ•œ๋‹ค.

stack์— ๋“ค์–ด๊ฐ„ ์ˆœ์„œ๋ฅผ ๋ณด๋ฉด ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค.

1=>2=>3=>4=>5=>6=>7=>8

๋”ฐ๋ผ์„œ ํŠธ๋ฆฌ์—์„œ BFS๋ฅผ ์‹คํ–‰ํ•˜์—ฌ ํƒ์ƒ‰์„ ํ•˜๋Š” ๊ฒƒ์€ ๋ ˆ๋ฒจ ์ˆœํšŒ๋ฅผ ํ•˜๋Š” ๊ฒƒ๊ณผ ๊ฐ™๋‹ค.

 

DFS

DFS๋Š” ์Šคํƒ์„ ์ด์šฉํ•˜์—ฌ ๊ตฌํ˜„ํ•œ๋‹ค.

 

์„ค๋ช…

ํŠธ๋ฆฌ๋กœ ์˜ˆ๋ฅผ ๋“ค์—ˆ์ง€๋งŒ, ๋ชจ๋“  ๊ทธ๋ž˜ํ”„์—์„œ ๋งˆ์ฐฌ๊ฐ€์ง€๋กœ ๋™์ž‘ํ•œ๋‹ค.

  1. ๋ฃจํŠธ ๋…ธ๋“œ๋ฅผ queue์— ๋„ฃ๋Š”๋‹ค.

 

  1. stack์˜ ๋…ธ๋“œ๋ฅผ peek(๋งจ ์œ„์˜ ๋…ธ๋“œ๋ฅผ ๋ณด๊ธฐ๋งŒ ํ•จ)ํ•œ ํ›„, ํ•ด๋‹น ๋…ธ๋“œ์˜ ์ธ์ ‘ ๋…ธ๋“œ๋ฅผ ํ•˜๋‚˜ stack์— ๋„ฃ๋Š”๋‹ค.

 

  1. ์œ„์˜ ๊ณผ์ •์„ ๋ฐ˜๋ณตํ•˜๋˜, peekํ•œ ๋…ธ๋“œ์˜ ์ธ์ ‘ ๋…ธ๋“œ๊ฐ€ ๋ชจ๋‘ ์™„๋ฃŒ์— ์žˆ๊ฑฐ๋‚˜ ์•„์˜ˆ ์—†๋‹ค๋ฉด ํ•ด๋‹น ๋…ธ๋“œ๋ฅผ stack์—์„œ ๊บผ๋‚ธ๋‹ค.

 

์ฝ”๋“œ

ํŠธ๋ฆฌ๊ฐ€ ์•„๋‹Œ ๊ทธ๋ž˜ํ”„์—์„œ์˜ BFS, DFS๋ฅผ ๋ฐฐ์—ด๋กœ ๊ตฌํ˜„ํ•ด๋ณด์ž.

#include <iostream>
#include <stack>
#include <queue>

using namespace std;

int memorize[8];

void BFS(int connect[][8]) {
    queue<int> q;
    q.push(1); // ๋ฃจํŠธ ๋„ฃ๊ธฐ
    do {
        int tmp = q.front(); q.pop();
        if (memorize[tmp] == 1)
            continue;
        memorize[tmp] = 1;
        cout << tmp << endl;
        for (int i = 1; i < 8; i++) {
            if (connect[tmp][i] == 1 && memorize[i]==0) { // ์ธ์ ‘ ๋…ธ๋“œ๋Š” ๋ชจ๋‘ ๋„ฃ๊ธฐ
                q.push(i);
            }
        }
    } while (!q.empty()); // queue๊ฐ€ ๋นŒ ๋•Œ๊นŒ์ง€

}

void DFS(int connect[][8], stack<int> & stk) {
    int tmp = stk.top(); // stack์— ์žˆ๋Š” ๋…ธ๋“œ ๊บผ๋‚ด๊ธฐ
    memorize[tmp] = 1;
    cout << tmp << endl;
    for (int i = 1; i < 8; i++) {
        if (connect[tmp][i] == 1 && memorize[i] == 0) { // ์ธ์ ‘ ๋…ธ๋“œ ํ•˜๋‚˜ ๋„ฃ๊ธฐ
            stk.push(i);
            DFS(connect, stk);
        }
    }
}

void setConnect(int arr[][8], int a, int b) {
    arr[a][b] = 1;
    arr[b][a] = 1;
}

int main() {
    int arr[8] = { 0,1,2,3,4,5,6,7 };
    int connect[8][8];
    setConnect(connect, 1, 2);
    setConnect(connect, 2, 3);
    setConnect(connect, 2, 6);
    setConnect(connect, 3, 4);
    setConnect(connect, 4, 6);
    setConnect(connect, 4, 5);
    setConnect(connect, 5, 7);

    //BFS(connect);
    /*
    stack<int> stk;
    stk.push(1); // ๋ฃจํŠธ ๋…ธ๋“œ ๋„ฃ๊ธฐ
    DFS(connect,stk);
    */
}

 

์ฐธ๊ณ 

https://m.blog.naver.com/ndb796/221230945092

๊ทธ๋ฆผ์œผ๋กœ ์ •๋ง ์ž˜ ์„ค๋ช…ํ•ด๋‘์—ˆ๋‹ค.

๋ฐ˜์‘ํ˜•