세상의 모든 알고리즘
[백준 18352번 python] 특정 거리의 도시 찾기 본문
https://www.acmicpc.net/problem/18352
from collections import deque
import sys
input = sys.stdin.readline
n,m,k,x = map(int,input().split())
graph = [[] for _ in range(n+1)]
visited = [-1] * (n+1)
visited[x] = 0
for _ in range(m):
a,b = map(int,input().split())
graph[a].append(b)
q = deque([x])
while q:
a = q.popleft()
for i in graph[a]:
if visited[i] == -1 :
q.append(i)
visited[i] = visited[a] +1
for i in range(1,n+1):
if k == visited[i]:
print(i)
if k not in visited:
print(-1)
간단한 BFS 탐색 문제라고 생각하고 몇번을 풀어도 시간초과라는 결과가 나와서
검색을 통해 sys.stdin.readline 구문을 사용해 input()사용을 했을때보다 시간을 절약해 풀 수 있었습니다.
'python' 카테고리의 다른 글
[백준 2606번 python] 바이러스 (0) | 2021.11.05 |
---|---|
[백준 2667 python] 단지번호 붙이기 (0) | 2021.11.04 |
[백준 2178번 python] 미로 탐색 문제 (0) | 2021.11.04 |
[백준 7576번 python] 토마토 문제 (0) | 2021.11.04 |
[이것이코딩테스트다 Python] 미로 탈출 (0) | 2021.11.03 |