18352 : 특정 거리의 도시 찾기
문제
코드
from collections import deque
import sys
input = sys.stdin.readline
n,m,k,x = map(int,input().split())
result = [-1]*(n+1)
result[x] = 0 #시작점
path = [[] for _ in range(n+1)]
for _ in range(m):
a,b = map(int,input().split())
path[a].append(b) #간선 연결
queue = deque([x])
while queue:
now = queue.popleft()
for nextcity in path[now]:
if result[nextcity] == False :
result[nextcity] = result[now]+1
queue.append(nextcity)
for i in range(n+1):
if result[i]==k:
print(i)
#없으면
if k not in result:
print(-1)
해설
from collections import deque
import sys
input = sys.stdin.readline
n,m,k,x = map(int,input().split())
result = [-1]*(n+1)
result[x] = 0 #시작점
path = [[] for _ in range(n+1)]
for _ in range(m):
a,b = map(int,input().split())
path[a].append(b) #간선 연결
queue = deque([x])
while queue:
now = queue.popleft()
for nextcity in path[now]:
if result[nextcity] == False :
result[nextcity] = result[now]+1
queue.append(nextcity)
for i in range(n+1):
if result[i]==k:
print(i)
#없으면
if k not in result:
print(-1)
-1로 초기화하고 갈때마다 1씩 증가시켜준다
Author And Source
이 문제에 관하여(18352 : 특정 거리의 도시 찾기), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@seochan99/18352-특정-거리의-도시-찾기저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)