📍 문제
📍 풀이
BFS 활용
- 사람 관계는 꼭 양뱡향으로 리스트에 삽입해 주어야 함
- 이중 for문을 돌면서 BFS를 실행
- 이때, 시작과 끝 사람이 같은 경우 (즉, 같은 사람일 경우) pass
- 한 사람이 다른 사람까지 가는 단계를 count에 저장
- 한 사람이 모든 다른 사람의 단계를 합쳐 케빈 베이컨 수 구함 (temp)
📍 코드
#include<iostream>
#include<vector>
#include<queue>
#include<cstring>
using namespace std;
int N, M;
int A, B;
bool visited[101];
vector<int> vec[101];
int cnt = 0;
void BFS(int start, int end) {
queue<pair<int, int>> q;
q.push({ start, 0 });
visited[start] = true;
while (!q.empty()) {
int cur = q.front().first;
int num = q.front().second;
q.pop();
if (cur == end) {
cnt = num;
break;
}
for (int i{ 0 }; i < vec[cur].size(); i++) {
if (!visited[vec[cur][i]]) {
q.push({ vec[cur][i], num + 1 });
visited[vec[cur][i]] = true;
}
}
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cin >> N >> M;
for (int i{ 0 }; i < M; i++) {
cin >> A >> B;
vec[A].push_back(B);
vec[B].push_back(A);
}
int min = 98765432;
int ans = 0;
for (int i{ 1 }; i <= N; i++) {
int temp = 0;
for (int j{ 1 }; j <= N; j++) {
memset(visited, false, sizeof(visited));
if (i != j) {
BFS(i, j);
temp += cnt;
cnt = 0;
}
}
if (min > temp) {
min = temp;
ans = i;
}
}
cout << ans;
}
'백준 & 프로그래머스' 카테고리의 다른 글
[프로그래머스] Lv.1 폰켓몬 C++ (0) | 2024.08.08 |
---|---|
[BOJ/백준] C++ 2468번 안전영역 (0) | 2024.01.12 |
[BOJ/백준] C++ 2178번 미로탐색 (0) | 2024.01.12 |
[BOJ/백준] C++ 2512번 예산 (0) | 2023.09.02 |
[C++ STL] 우선순위 큐 (priority queue) (0) | 2023.07.13 |