[๋ฐฑ์ค€-16928] ๋ฑ€๊ณผ ์‚ฌ๋‹ค๋ฆฌ ๊ฒŒ์ž„

๐Ÿ“š Problem Solving/Baekjoon

 

16928๋ฒˆ: ๋ฑ€๊ณผ ์‚ฌ๋‹ค๋ฆฌ ๊ฒŒ์ž„

์ฒซ์งธ ์ค„์— ๊ฒŒ์ž„ํŒ์— ์žˆ๋Š” ์‚ฌ๋‹ค๋ฆฌ์˜ ์ˆ˜ N(1 ≤ N ≤ 15)๊ณผ ๋ฑ€์˜ ์ˆ˜ M(1 ≤ M ≤ 15)์ด ์ฃผ์–ด์ง„๋‹ค. ๋‘˜์งธ ์ค„๋ถ€ํ„ฐ N๊ฐœ์˜ ์ค„์—๋Š” ์‚ฌ๋‹ค๋ฆฌ์˜ ์ •๋ณด๋ฅผ ์˜๋ฏธํ•˜๋Š” x, y (x < y)๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. x๋ฒˆ ์นธ์— ๋„์ฐฉํ•˜๋ฉด, y๋ฒˆ ์นธ์œผ

www.acmicpc.net

import sys
from collections import deque

distance = [-1] * 101


def bfs(x):
    queue = deque()
    queue.append(x)
    distance[x] = 0
    while queue:
        x = queue.popleft()
        for i in range(1, 7):
            nx = x + i
            if nx > 100:
                continue
            if graph[nx]:
                if (
                    distance[graph[nx][0]] == -1
                    or distance[graph[nx][0]] > distance[x] + 1
                ):
                    distance[graph[nx][0]] = distance[x] + 1
                    queue.append(graph[nx][0])
            else:
                if distance[nx] == -1 or distance[nx] > distance[x] + 1:
                    distance[nx] = distance[x] + 1
                    queue.append(nx)


graph = [[] for _ in range(101)]
n, m = map(int, sys.stdin.readline().split())
for _ in range(n):
    x, y = map(int, sys.stdin.readline().split())
    graph[x].append(y)
for _ in range(m):
    u, v = map(int, sys.stdin.readline().split())
    graph[u].append(v)
bfs(1)
print(distance[-1])

 

ํ•ด์„ค

bfs๋กœ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ๋Š” ๋ฌธ์ œ์˜€๋‹ค. ์‚ฌ๋‹ค๋ฆฌ๋‚˜ ๋ฑ€์ด ์œ„์น˜ํ•œ ๊ณณ์€ ์ฃผ์–ด์ง„ ์ขŒํ‘œ๋กœ ์ด๋™ ํ›„, ์ถœ๋ฐœ ๊ฐ’์— 1์„ ๋”ํ•ด์ฃผ๋ฉด ๋œ๋‹ค.