Post

baekjoon 1260:DFS와 BFS

baekjoon 1260 DFS와 BFS

1260번 DFS와 BFS

접근

DFS는 깊이 우선 탐색이고, BFS는 넓이 우선 탐색이다.

코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <iostream>
#include <vector>
#include <queue>

using namespace std;
void dfs(vector<vector<int>>& graph, vector<int>& visited, int s);
int main(){
  ios::sync_with_stdio(false);
  cin.tie(0);

  int n, m, s;
  cin >> n >> m >> s;

  vector<vector<int>> graph(n, vector<int>(n, 0));

  for(int i = 0; i < m; i++){
    int a, b;
    cin >> a >> b;
    graph[a-1][b-1] = 1;
    graph[b-1][a-1] = 1;
  }
  //dfs
  vector<int> visited(n, 0);
  dfs(graph, visited, s-1);
  
  cout << "\n";

  //bfs
  for(int i = 0; i < n; i++){
    visited[i] = 0;
  }
  queue<int> q;
  q.push(s-1);
  visited[s-1] = 2;
  while(!q.empty()){
    int cur = q.front();
    q.pop();
    for(int i = 0; i < n; i++){
      if(graph[cur][i] == 1 && visited[i] == 0){
        visited[i] = 1;
        q.push(i);
      }
    }
    visited[cur] = 2;
    cout << cur+1 << " ";
  }
  
  
  
  return 0;
}
void dfs(vector<vector<int>>& graph, vector<int>& visited, int s){
  visited[s] = 1;
  cout << s+1 << " ";
  for(int i = 0; i < graph.size(); i++){
    if(graph[s][i] == 1 && visited[i] == 0){
      dfs(graph, visited, i);
    }
  }
}

다른 접근

dfs를 stack으로 했을 수도 있다.

배운 점

dfs는 stack, bfs는 queue를 이용한다. dfs의 stack은 재귀함수로 변형시킬 수 있다.

This post is licensed under CC BY 4.0 by the author.