문제) 백준 - BFS - 숨바꼭질
https://www.acmicpc.net/problem/6118
6118번: 숨바꼭질
재서기는 수혀니와 교외 농장에서 숨바꼭질을 하고 있다. 농장에는 헛간이 많이 널려있고 재서기는 그 중에 하나에 숨어야 한다. 헛간의 개수는 N(2 <= N <= 20,000)개이며, 1 부터 샌다고 하자. 재
www.acmicpc.net
최대 거리에 위치한 헛간, 최대 거리, 같은 거리에 있는 헛간 개수를 출력하기 위해 BFS를 통해 해결합니다.
C++ 소스코드)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void bfs(int src){ | |
queue<p> q; | |
q.push({src, 0}); | |
visited[src] = true; | |
while(!q.empty()){ | |
int now = q.front().first; | |
int cost = q.front().second; | |
q.pop(); | |
for(int next: graph[now]){ | |
if(!visited[next]){ | |
if(maxCost < cost + 1){ | |
maxCost = cost + 1; | |
ans.clear(); | |
ans.push_back(next); | |
} | |
else if(maxCost == cost + 1){ | |
ans.push_back(next); | |
} | |
q.push({next, cost + 1}); | |
visited[next] = true; | |
} | |
} | |
} | |
} |
Full Code)
GitHub - Chocochip101/BOJ_Solution: BOJ Solutions
BOJ Solutions. Contribute to Chocochip101/BOJ_Solution development by creating an account on GitHub.
github.com
반응형
'PS(Problem Solving) > 백준_BOJ' 카테고리의 다른 글
[백준] 5618번 - 공약수 (C++) 문제 및 풀이 (0) | 2022.02.21 |
---|---|
[백준] 3584번 - 가장 가까운 공통 조상 (C++) 문제 및 풀이 (0) | 2022.02.19 |
[백준] 2302번 - 극장 좌석 (C++) 문제 및 풀이 (0) | 2022.02.18 |
[백준] 21919번 - 소수 최소 공배수 (C++) 문제 및 풀이 (0) | 2022.02.18 |
[백준] 21610번 - 마법사 상어와 비바라기 (C++) 문제 및 풀이 (0) | 2022.02.17 |
댓글