๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm ๐Ÿง‘๐Ÿป‍๐Ÿ’ป/๋ฐฑ์ค€(BOJ)

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

by dkswnkk 2021. 11. 2.
 

1260๋ฒˆ: DFS์™€ BFS

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

www.acmicpc.net

#include <iostream>
#include <queue>
#include <vector>
#include <cstring>

using namespace std;

int visited[1001];
int map[1001][1001];
queue<int>q;
int N, M, V;

void dfs(int n) {
    visited[n] = 1; //ํ˜„์žฌ ๋…ธ๋“œ๋ฅผ ๋ฐฉ๋ฌธ์ฒ˜๋ฆฌ
    cout << n << ' ';
    for (int i = 1; i <= N; i++) {
        if (!visited[i] && map[n][i]) {
            dfs(i);
        }
    }
}

void bfs(int n) {
    q.push(n);
    visited[n] = 1;
    while (!q.empty()) {
        int x = q.front(); //ํ์—์„œ ํ•˜๋‚˜์˜ ์›์†Œ๋ฅผ ๋ฝ‘์•„ ์ถœ๋ ฅ
        q.pop();
        cout << x << ' ';
        for (int i = 1; i <=N; i++) {
            if (!visited[i] && map[x][i]) {
                q.push(i);
                visited[i] = 1;
            }
        }
    }
}


int main() {
    cin >> N >> M >> V;

    for (int i = 0; i < M; i++) { // ๊ฐ„์„  ์—ฐ๊ฒฐ
        int a, b;
        cin >> a >> b;
        map[a][b] = 1;
        map[b][a] = 1;
    }
    dfs(V);
    cout << "\n";
    memset(visited, 0, sizeof(visited));
    bfs(V);
}

๋Œ“๊ธ€