Algorithm/Baekjoon
[Algorithm] Baekjoon 2644번 : 촌수계산
MaxLevel
2023. 2. 8. 21:50
https://www.acmicpc.net/problem/2644
2644번: 촌수계산
사람들은 1, 2, 3, …, n (1 ≤ n ≤ 100)의 연속된 번호로 각각 표시된다. 입력 파일의 첫째 줄에는 전체 사람의 수 n이 주어지고, 둘째 줄에는 촌수를 계산해야 하는 서로 다른 두 사람의 번호가 주어
www.acmicpc.net
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
|
struct Node
{
int node;
int count;
};
vector<vector<int>> graph(101);
bool visited[101];
int BFS(int start, int target)
{
queue<Node> q;
q.push({ start,0 });
visited[start] = true;
while (!q.empty())
{
int curNode = q.front().node;
int curCount = q.front().count;
q.pop();
if (curNode == target)
{
return curCount;
}
for (int i = 0; i < graph[curNode].size(); ++i)
{
int nextNode = graph[curNode][i];
if (visited[nextNode]) continue;
q.push({ nextNode,curCount + 1 });
visited[nextNode] = true;
}
}
return -1;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int n, s, e, m;
int a, b;
cin >> n >> s >> e >> m;
for (int i = 0; i < m; ++i)
{
cin >> a >> b;
graph[a].push_back(b);
graph[b].push_back(a);
}
cout << BFS(s, e);
}
|
cs |