๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
์•Œ๊ณ ๋ฆฌ์ฆ˜ ๋ฌธ์ œ ํ’€์ด/DFS,BFS

[๋ฐฑ์ค€]2644๋ฒˆ: ์ดŒ์ˆ˜๊ณ„์‚ฐ

by syLim___ 2023. 2. 18.
728x90

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

 

2644๋ฒˆ: ์ดŒ์ˆ˜๊ณ„์‚ฐ

์‚ฌ๋žŒ๋“ค์€ 1, 2, 3, …, n (1 ≤ n ≤ 100)์˜ ์—ฐ์†๋œ ๋ฒˆํ˜ธ๋กœ ๊ฐ๊ฐ ํ‘œ์‹œ๋œ๋‹ค. ์ž…๋ ฅ ํŒŒ์ผ์˜ ์ฒซ์งธ ์ค„์—๋Š” ์ „์ฒด ์‚ฌ๋žŒ์˜ ์ˆ˜ n์ด ์ฃผ์–ด์ง€๊ณ , ๋‘˜์งธ ์ค„์—๋Š” ์ดŒ์ˆ˜๋ฅผ ๊ณ„์‚ฐํ•ด์•ผ ํ•˜๋Š” ์„œ๋กœ ๋‹ค๋ฅธ ๋‘ ์‚ฌ๋žŒ์˜ ๋ฒˆํ˜ธ๊ฐ€ ์ฃผ์–ด

www.acmicpc.net


#include <iostream>

using namespace std;

int n,m;
int graph[101][101];
bool visited[101];
int cnt=0; 
int ans=-1;

void dfs(int x,int y){
    if(x==y) ans=cnt;
    visited[x]=1;
    cnt++;
    for(int i=0;i<=n;i++){
        if(graph[x][i]==1 && !visited[i]) dfs(i,y);
    }
    cnt--;
    
    return;
}

int main()
{
    cin>>n;
    int x,y;
    cin>>x>>y;
    cin>>m;
    for(int i=0;i<m;i++){
        int a,b;
        cin>>a>>b;
        graph[a][b]=1;
        graph[b][a]=1;
    }

    if(x==y){
        cout<<0; return 0;
    }
    
    dfs(x,y);
    cout<<ans;
    
    return 0;
}
728x90