๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

Algorithm/๋ฐฑ์ค€

[๋ฐฑ์ค€] #18352 ํŠน์ • ๊ฑฐ๋ฆฌ์˜ ๋„์‹œ ์ฐพ๊ธฐ (Python)

1. ๋ฌธ์ œ ์„ค๋ช…

๋ฌธ์ œ ๋งํฌ

  • ์ž…๋ ฅ
    • ์ฒซ์งธ ์ค„์— ๋„์‹œ์˜ ๊ฐœ์ˆ˜ N, ๋„๋กœ์˜ ๊ฐœ์ˆ˜ M, ๊ฑฐ๋ฆฌ ์ •๋ณด K, ์ถœ๋ฐœ ๋„์‹œ์˜ ๋ฒˆํ˜ธ X
    • ๋‘˜์งธ ์ค„๋ถ€ํ„ฐ M๊ฐœ์˜ ์ค„์— ๊ฑธ์ณ์„œ ๋‘ ๊ฐœ์˜ ์ž์—ฐ์ˆ˜ A, B๊ฐ€ ๊ณต๋ฐฑ์„ ๊ธฐ์ค€์œผ๋กœ ๊ตฌ๋ถ„๋˜์–ด ์ฃผ์–ด์ง, ์ด๋Š” A๋ฒˆ ๋„์‹œ์—์„œ B๋ฒˆ ๋„์‹œ๋กœ ์ด๋™ํ•˜๋Š” ๋‹จ๋ฐฉํ–ฅ ๋„๋กœ๊ฐ€ ์กด์žฌํ•œ๋‹ค๋Š” ์˜๋ฏธ
  • ์ถœ๋ ฅ : [3,4,2,1,5] ์‹คํŒจ์œจ์ด ๋†’์€ ์Šคํ…Œ์ด์ง€์ˆœ์œผ๋กœ ์ถœ๋ ฅ, ์ตœ๋‹จ ๊ฑฐ๋ฆฌ๊ฐ€ K์ธ ๋„์‹œ๊ฐ€ ํ•˜๋‚˜๋„ ์กด์žฌํ•˜์ง€ ์•Š์œผ๋ฉด -1

2. ์ฝ”๋“œ

solution1.py

# -*- coding: utf-8 -*-
#๋…ธ๋“œ, ๊ฐ„์„  graph ๋งŒ๋“ค๊ธฐ
from collections import deque
import sys
input = sys.stdin.readline
N,M,K,X = map(int, input().split())
graph = [[] for _ in range(N+1)] #๊ฐ ๋…ธ๋“œ(0~N)๊ฐœ ๋ณ„๋กœ ๋ฆฌ์ŠคํŠธ๊ฐ€ ์กด์žฌํ•˜๋„๋ก ์ดˆ๊ธฐํ™”
distance = [0 for _ in range(N+1)]
visited = [False]*(N+1)
#๋…ธ๋“œ ์—ฐ๊ฒฐ์ •๋ณด๋ฅผ ์ฐธ๊ณ ํ•˜์—ฌ graph list์— ์ถ”๊ฐ€
for _ in range(M):
    a, b = map(int, input().split())
    graph[a].append(b)

#์ถœ๋ฐœ๋…ธ๋“œ X๋กœ๋ถ€ํ„ฐ ๊ฐ ๋…ธ๋“œ๊นŒ์ง€ ๊ฑฐ๋ฆฌ๋ฅผ ๊ณ„์‚ฐํ•˜๊ณ  ๊ฑฐ๋ฆฌ๊ฐ€ K์ธ ๋…ธ๋“œ๋งŒ ์ถœ๋ ฅ
def bfs(graph, start, visited, distance):
    queue = deque([start])
    visited[start] = True #ํ˜„์žฌ ๋…ธ๋“œ ๋ฐฉ๋ฌธ์ฒ˜๋ฆฌ
    distance[start] = 0
    while queue:
        v = queue.popleft() #ํ˜„์žฌ๋…ธ๋“œ
        for i in graph[v]: #ํ•ด๋‹น ๋…ธ๋“œ์˜ ์ธ์ ‘ ๋…ธ๋“œ๋“ค ํ™•์ธ
            if not visited[i]:#์•„์ง ๋ฐฉ๋ฌธํ•˜์ง€์•Š์€ ์ธ์ ‘๋…ธ๋“œ๋“ค์„
                queue.append(i) #์ฐพ๋Š” ์กฑ์กฑ ๋‹ค ํ์— ์‚ฝ์ž…
                visited[i] = True #๋ฐฉ๋ฌธ์ฒ˜๋ฆฌ
                distance[i] += distance[v]+ 1#

    exist  = False
    for i, c in enumerate(distance):
        if c == K:
            print(i)
            exist = True
    if exist == False:
            print(-1)

bfs(graph,X,visited,distance)

3. ํšŒ๊ณ 

  • ์ฒ˜์Œ์— ํ’€ ๋•Œ ๋Ÿฐํƒ€์ž„ ์—๋Ÿฌ(IndexError)๊ฐ€ ๋‚ฌ๋‹ค.
  • visited = [False]*(N+1) ๋กœ ํ•ด์•ผํ•˜๋Š”๋ฐ, visited = [False]*9 ๋กœ ๋˜์–ด ์žˆ์—ˆ๋‹ค. ใ… ใ… 
  • bfs ๋ฅผ ํ†ตํ•ด ์•„์ง ๋ฐฉ๋ฌธํ•˜์ง€ ์•Š์€ ์ธ์ ‘๋…ธ๋“œ i๋ฅผ ์ฐพ์•˜์„ ๋•Œ, ๋ฐฉ๋ฌธ์ฒ˜๋ฆฌ๋ฅผ ํ•ด์ฃผ๋Š” ๋ถ€๋ถ„์—์„œ ์ด์ „ ๋…ธ๋“œ๊นŒ์ง€์˜ ๊ฑฐ๋ฆฌ๋ฅผ ๋‚˜ํƒ€๋‚ด๋Š” distance[v]์— +1 ์„ ํ•ด์„œ ์ƒˆ๋กญ๊ฒŒ ๋ฐฉ๋ฌธํ•˜๋Š” ๋…ธ๋“œ๊นŒ์ง€์˜ ๊ฑฐ๋ฆฌ(distance[i])์— ์ €์žฅํ•ด์ค€๋‹ค.