BFS
#include <stdio.h>
#include <iostream>
#include <queue>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
int map[110][110];
int people;
int relation;
int s, e;
int ans;
queue<int> q;
int visited[110];
void BFS()
{
visited[s] = 1;
q.push(s);
while(!q.empty())
{
int now = q.front();
q.pop();
if(now == e)
{
return;
}
for(int i = 1; i <= people; i++)
{
if(map[now][i] == 1 && visited[i] == 0)
{
visited[i] = visited[now] + 1;
q.push(i);
}
}
}
}
int main(void)
{
// freopen("B2644_input.txt", "r", stdin);
cin >> people;
cin >> s >> e;
cin >> relation;
for(int i = 1; i <= relation; i++)
{
int a, b;
cin >> a >> b;
map[a][b] = 1;
map[b][a] = 1;
}
BFS();
if(visited[e] == 0)
{
cout << -1;
}
else
{
cout << visited[e]-1;
}
return 0;
}
|
cs |
Floyd-Warshall
#include <stdio.h>
#include <iostream>
#include <queue>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
int map[110][110];
int visited[110][110];
int people;
int relation;
int s, e;
int ans;
void floyd()
{
for(int k = 1; k <= people; k++)
{
for(int i = 1; i <= people; i++)
{
for(int j = 1; j <= people; j++)
{
if(i == j)
{
continue;
}
if(map[i][k] != 0 && map[k][j] != 0 && visited[i][j] == 0)
{
visited[i][j] = 1;
visited[j][i] = 1;
map[i][j] = map[i][k] + map[k][j];
map[j][i] = map[i][k] + map[k][j];
}
}
}
}
}
int main(void)
{
// freopen("B2644_input.txt", "r", stdin);
cin >> people;
cin >> s >> e;
cin >> relation;
for(int i = 1; i <= relation; i++)
{
int a, b;
cin >> a >> b;
map[a][b] = 1;
map[b][a] = 1;
}
floyd();
if(map[s][e] == 0)
{
cout << -1;
}
else
{
cout << map[s][e];
}
return 0;
}
|
cs |
'Baekjoon > Graph' 카테고리의 다른 글
[백준 1507] 궁금한 민호 (Floyd-Warshall) (C/C++) (★★) (0) | 2020.02.08 |
---|---|
[백준 5567] 결혼식 (Floyd-Warshall) (C/C++) (0) | 2020.02.07 |
[백준 11404] 플로이드 (Floyd-Warshall) (C/C++) (0) | 2020.02.07 |
[백준 1613] 역사 (Floyd-Warshall) (C/C++) (★) (0) | 2019.11.20 |
[백준 11403] 경로찾기 (Floyd-Warshall) (C/C++) (0) | 2019.11.20 |