백준 알고리즘 2644번 - 촌수계산
2019. 7. 9. 14:19ㆍ프로그래밍/백준 알고리즘
전형적인 bfs를 이용해서 푸는 문제.
시간 복잡도 : bfs이고, 인접행렬로 구했으므로 o(n^2)
소스코드
#include <iostream>
#include <algorithm>
#include <queue>
#include <vector>
using namespace std;
int connected[101][101]={0,};
bool visited[101]={false,};
int counts[101]={0,};
int p,rel,from,to;
void bfs(int start)
{
visited[start]=1;
queue<int> q;
q.push(start);
while(!q.empty()){
int now=q.front();
q.pop();
for(int i=1;i<=p;i++){
if(connected[now][i]==1 && !visited[i]){
counts[i]=counts[now]+1;
q.push(i);
visited[i]=1;
}
}
}
}
int main()
{
cin>>p>>from>>to>>rel;
for(int i=1;i<=rel;i++){
int a,b;
cin>>a>>b;
connected[a][b]=1;
connected[b][a]=1;
}
bfs(from);
if(counts[to]==0) cout<<"-1";
else cout<<counts[to];
}
'프로그래밍 > 백준 알고리즘' 카테고리의 다른 글
백준 알고리즘 문제 풀이 10610번 - 30 (0) | 2019.09.05 |
---|---|
백준 알고리즘 1325번 - 효율적인 해킹 (0) | 2019.07.17 |
백준 알고리즘 1783번 - 병든 나이트 (0) | 2019.06.11 |
백준 알고리즘 1744번 - 수 묶기 (0) | 2019.06.11 |
백준 알고리즘 1449번 - 수리공 항승 (0) | 2019.05.31 |