본문 바로가기
프로그래밍/문제풀이

[dfs] 백준 2644 촌수계산

by 하용권 2019. 3. 27.

https://www.acmicpc.net/problem/2644


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
#include <iostream>
#include <vector>
using namespace std;
vector<int> v[100];
bool visited[100= {0};
bool chk = 0;
 
void dfs(int start, int target, int ret){
    if(start == target)    {cout << ret; chk = true;}
    
    for(int i = 0; i  <v[start].size(); i++){
        int tmp = v[start][i];
        
        if(visited[tmp]) continue;
        visited[tmp] = true;
        dfs(tmp,target,ret+1);
    }
 
}
 
int main(){
    int target1,target2,n,m,x,y;
    
    cin >> n >> target1 >> target2 >> m;
    
    for(int i = 0; i < m; i++){
        cin >> x >> y;
        v[x].push_back(y);
        v[y].push_back(x);
    }
    dfs(target1,target2,0);
    if(!chk) cout << -1;
 
}
cs


반응형