728x90
문제 링크: https://www.acmicpc.net/problem/6118
6118번: 숨바꼭질
재서기는 수혀니와 교외 농장에서 숨바꼭질을 하고 있다. 농장에는 헛간이 많이 널려있고 재서기는 그 중에 하나에 숨어야 한다. 헛간의 개수는 N(2 <= N <= 20,000)개이며, 1 부터 샌다고 하자. 재
www.acmicpc.net
문제 풀이
기본적인 BFS 최단거리 문제다. 갱신에 유의하자.
코드
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
from collections import deque | |
import sys | |
input = sys.stdin.readline | |
MIN = -int(1e9) | |
MAX = int(1e9) | |
n, m = map(int, input().split()) | |
graph = [[] for _ in range(n+1)] | |
visited = [False] * (n+1) | |
for _ in range(m): | |
a, b = map(int, input().split()) | |
graph[a].append(b) | |
graph[b].append(a) | |
dist_ans = MIN | |
min_ans = MAX | |
count_ans = 0 | |
def bfs(start, d): | |
global dist_ans, count_ans, min_ans | |
q = deque() | |
q.append((start, d)) | |
while q: | |
now, dist = q.popleft() | |
visited[now] = True | |
if dist_ans < dist: | |
min_ans = now | |
dist_ans = dist | |
count_ans = 1 | |
elif dist_ans == dist: | |
min_ans = min(min_ans, now) | |
count_ans += 1 | |
for i in graph[now]: | |
if not visited[i]: | |
visited[i] = True | |
q.append((i, dist+1)) | |
bfs(1, 0) | |
print(min_ans, dist_ans, count_ans) |
728x90
'BOJ' 카테고리의 다른 글
[BOJ][Python] 백준 11403번 - 경로 찾기 (0) | 2021.10.01 |
---|---|
[BOJ][Python] 백준 15711번 - 환상의 짝꿍 (0) | 2021.09.29 |
[BOJ][Python] 백준 15728번 - 에리 - 카드 (0) | 2021.09.29 |
[BOJ][Python] 백준 16917번 - 양념 반 후라이드 반 (0) | 2021.09.28 |
[BOJ][Python] 백준 17403번 - 가장 높고 넓은 성 (0) | 2021.09.26 |