๋ฌธ์ 
๊ทธ๋ํ๋ฅผ DFS๋ก ํ์ํ ๊ฒฐ๊ณผ์ BFS๋ก ํ์ํ ๊ฒฐ๊ณผ๋ฅผ ์ถ๋ ฅํ๋ ํ๋ก๊ทธ๋จ์ ์์ฑํ์์ค. ๋จ, ๋ฐฉ๋ฌธํ ์ ์๋ ์ ์ ์ด ์ฌ๋ฌ ๊ฐ์ธ ๊ฒฝ์ฐ์๋ ์ ์  ๋ฒํธ๊ฐ ์์ ๊ฒ์ ๋จผ์  ๋ฐฉ๋ฌธํ๊ณ , ๋ ์ด์ ๋ฐฉ๋ฌธํ ์ ์๋ ์ ์ด ์๋ ๊ฒฝ์ฐ ์ข ๋ฃํ๋ค. ์ ์  ๋ฒํธ๋ 1๋ฒ๋ถํฐ N๋ฒ๊น์ง์ด๋ค.
์ ๋ ฅ
์ฒซ์งธ ์ค์ ์ ์ ์ ๊ฐ์ N(1 ≤ N ≤ 1,000), ๊ฐ์ ์ ๊ฐ์ M(1 ≤ M ≤ 10,000), ํ์์ ์์ํ ์ ์ ์ ๋ฒํธ V๊ฐ ์ฃผ์ด์ง๋ค. ๋ค์ M๊ฐ์ ์ค์๋ ๊ฐ์ ์ด ์ฐ๊ฒฐํ๋ ๋ ์ ์ ์ ๋ฒํธ๊ฐ ์ฃผ์ด์ง๋ค. ์ด๋ค ๋ ์ ์  ์ฌ์ด์ ์ฌ๋ฌ ๊ฐ์ ๊ฐ์ ์ด ์์ ์ ์๋ค. ์ ๋ ฅ์ผ๋ก ์ฃผ์ด์ง๋ ๊ฐ์ ์ ์๋ฐฉํฅ์ด๋ค.
์ถ๋ ฅ
์ฒซ์งธ ์ค์ DFS๋ฅผ ์ํํ ๊ฒฐ๊ณผ๋ฅผ, ๊ทธ ๋ค์ ์ค์๋ BFS๋ฅผ ์ํํ ๊ฒฐ๊ณผ๋ฅผ ์ถ๋ ฅํ๋ค. V๋ถํฐ ๋ฐฉ๋ฌธ๋ ์ ์ ์์๋๋ก ์ถ๋ ฅํ๋ฉด ๋๋ค.
ํ์ด
https://dev-minji.tistory.com/76
[๊ฐ๋ ] DFS์ BFS
๐ ์ ์ 01. DFS(Depth First Search) : ๊น์ด ์ฐ์ ํ์) ๋ฃจํธ ๋ ธํธ์์ ์์ํด์ ๋ค์ ๋ถ๊ธฐ๋ก ๋์ด๊ฐ๊ธฐ ์ ์ ํด๋น ๋ถ๊ธฐ๋ฅผ ์๋ฒฝํ๊ฒ ํ์ํ๋ ๋ฐฉ๋ฒ. ๋ชจ๋ ๋ ธ๋๋ฅผ ๋ฐฉ๋ฌธํ๊ณ ์ ํ๋ ๊ฒฝ์ฐ์ ์ฌ์ฉํ๋ค. ์คํ(
dev-minji.tistory.com
// 1260๋ฒ DFS์ BFS
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
#define MAX 10001
int N, M, V; // ์ ์  ๊ฐ์, ๊ฐ์  ๊ฐ์, ์์ ์ ์ 
vector<int> graph[MAX]; // ์ธ์  ํ๋ ฌ ๊ทธ๋ํ
bool isVisited[MAX] = {false, }; // ์ ์  ๋ฐฉ๋ฌธ ์ฌ๋ถ
queue<int> q;
// DFS : ๋ฐฉ๋ฌธํ ๋
ธ๋์์ ์์ง ๋ฐฉ๋ฌธํ์ง ์์ ์ธ์ ํ ๋
ธ๋๋ก ์ฎ๊ฒจ๊ฐ๋ ์
void DFS(int v){
  isVisited[v] = true; // ๋ฐฉ๋ฌธ ํ์
  cout << v << " ";
  for (int i=0; i<graph[v].size(); i++){
    int next = graph[v][i];
    // ๋ฐฉ๋ฌธํ์ง ์์ ๊ฒฝ์ฐ
    if (isVisited[next] == false)
      DFS(next); // ์ฌ๊ทํจ์ ํธ์ถ
  }
}
// BFS : ๋ฐฉ๋ฌธํ ๋
ธ๋๋ก๋ถํฐ ์์ง ๋ฐฉ๋ฌธํ์ง ์์ ์ธ์ ํ ๋ชจ๋  ๋
ธ๋๋ฅผ ํ์ ์ถ๊ฐํ๋ ๋ฐฉ์
void BFS(int v){
  q.push(v); // ๋ฃจํธ ๋
ธ๋ ์ฝ์
  isVisited[v] = true;
  while(!q.empty()){
    int cur = q.front();
    q.pop();
    cout << cur << " ";
    for (int i=0; i<graph[cur].size(); i++){
      int next = graph[cur][i];
      // ๋ฐฉ๋ฌธํ์ง ์์ ๊ฒฝ์ฐ
      if (isVisited[next] == false){
        // ํ์ ๋ฃ์ด์ฃผ๊ณ  ๋ฐฉ๋ฌธํ์์ ํ์
        q.push(next);
        isVisited[next] = true;
      }
    }
  }
}
int main(){
  queue<int> q; // BFS์ฉ
  cin >> N >> M >> V;
  for (int i=0; i<M; i++){
    int u, v;
    cin >> u >> v;
    graph[u].push_back(v);
    graph[v].push_back(u);
  }
  // sort : ํ๋์ ์ ์ ์์ ๋ค์์ ํ์ํ  ๋ node์ ์์ฐจ์ ์ผ๋ก ์ ๊ทผํด์ผ ํจ
  for (int i=0; i<MAX; i++){
    sort(graph[i].begin(), graph[i].end());
  }
  DFS(V);
  cout << "\n";
  fill_n(isVisited, MAX, false); // ๋ฐฉ๋ฌธ ์ฌ๋ถ ์ด๊ธฐํ
  BFS(V);
}'โจ Algorithm' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
| [๋ฐฑ์ค/C++] 10870๋ฒ : ํผ๋ณด๋์น ์ 5 (0) | 2021.08.24 | 
|---|---|
| [๋ฐฑ์ค/C++] 10872๋ฒ : ํฉํ ๋ฆฌ์ผ (0) | 2021.08.24 | 
| [๊ฐ๋ ] DFS์ BFS (0) | 2021.08.24 | 
| [ํ๋ก๊ทธ๋๋จธ์ค/C++] ํ๊ฒ ๋๋ฒ(DFS) (0) | 2021.08.24 | 
| [ํ๋ก๊ทธ๋๋จธ์ค/C++] ์ฒด์ก๋ณต(Greedy) (0) | 2021.08.24 | 
 
										
									
๋๊ธ