DevYoon

[๋ฐฑ์ค€] 16928. ๋ฑ€๊ณผ ์‚ฌ๋‹ค๋ฆฌ ๊ฒŒ์ž„ (Python) ๋ณธ๋ฌธ

PS/Baekjoon

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

gimewn 2022. 9. 20. 23:29

link ๐Ÿ”— https://www.acmicpc.net/problem/16928

 

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

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

www.acmicpc.net

 

๐Ÿ ์‚ฌ๋‹ค๋ฆฌ๋‚˜ ๋ฑ€์„ ๋งŒ๋‚˜๋ฉด ์œ„์น˜์˜ ๋ณ€ํ™”๊ฐ€ ์ผ์–ด๋‚จ

๐Ÿ 1์—์„œ ์ถœ๋ฐœํ•˜์—ฌ 100์— ๋„์ฐฉํ•˜๊ธฐ๊นŒ์ง€ ์ฃผ์‚ฌ์œ„๋ฅผ ์ตœ์†Œ๋กœ ๊ตด๋ฆด ๋•Œ๋ฅผ ์ฐพ๋Š” ๋ฌธ์ œ

๐Ÿ ๊ฐ„๋‹จํ•œ BFS ๋ฌธ์ œ๋กœ, ์ด๋™ํ•œ ์นธ์ด ์‚ฌ๋‹ค๋ฆฌ๋‚˜ ๋ฑ€์ด ์กด์žฌํ•˜๋Š”์ง€ ํŽธํ•˜๊ฒŒ ํƒ์ƒ‰ํ•˜๊ธฐ ์œ„ํ•ด ๋”•์…”๋„ˆ๋ฆฌ๋กœ ์‚ฌ๋‹ค๋ฆฌ์™€ ๋ฑ€์˜ ์ •๋ณด๋ฅผ ์ €์žฅํ–ˆ๋‹ค.

 

import sys
from collections import deque

def BFS():
    q = deque()
    q.append((1, 0))
    visit = [0]*101 # ๋ฐฉ๋ฌธ ์ฒดํฌ
    visit[1] = 1
    while q:
        now, cnt = q.popleft()
        if now == 100: # 100์— ๋„๋‹ฌํ•˜๋ฉด cnt ์ถœ๋ ฅ
            return cnt
        for num in range(1, 7): # 1๋ถ€ํ„ฐ 6๊นŒ์ง€ ์ฃผ์‚ฌ์œ„
            tmp = now+num
            if tmp <= 100: # 100 ์ดˆ๊ณผํ•˜๋ฉด ์ด๋™ ๋ถˆ๊ฐ€๋Šฅ
                if visit[tmp]: continue # ๋ฐฉ๋ฌธํ•œ ์  ์žˆ์œผ๋ฉด ์ดํ›„ ๋กœ์ง ์ฒ˜๋ฆฌ X
                if tmp in ladder.keys(): # ์‚ฌ๋‹ค๋ฆฌ ์‹œ์ž‘ ์ง€์ ์— ์ด๋™ ๊ฒฐ๊ณผ๊ฐ€ ์žˆ์œผ๋ฉด
                    visit[tmp] = 1 # ์ด๋™ ๊ฒฐ๊ณผ์— ๋ฐฉ๋ฌธ ์ฒดํฌ
                    visit[ladder[tmp]] = 1 # ์‚ฌ๋‹ค๋ฆฌ ํƒ€๊ณ  ์˜ฌ๋ผ๊ฐ„ ๊ณณ๋„ ๋ฐฉ๋ฌธ ์ฒดํฌ
                    q.append((ladder[tmp], cnt+1)) # q์— append
                elif tmp in snake.keys(): # ๋ฑ€ ์‹œ์ž‘ ์ง€์ ์— ์ด๋™ ๊ฒฐ๊ณผ๊ฐ€ ์žˆ์œผ๋ฉด
                    visit[tmp] = 1 # ์ด๋™ ๊ฒฐ๊ณผ์— ๋ฐฉ๋ฌธ ์ฒดํฌ
                    visit[snake[tmp]] = 1 # ๋ฑ€ ํƒ€๊ณ  ๋‚ด๋ ค๊ฐ„ ๊ณณ๋„ ๋ฐฉ๋ฌธ ์ฒดํฌ
                    q.append((snake[tmp], cnt+1)) # q์— append
                else:
                    visit[tmp] = 1
                    q.append((now+num, cnt+1))

input = sys.stdin.readline

N, M = map(int, input().split())

ladder = {}
snake = {}

# ์ถ”ํ›„ ํƒ์ƒ‰์„ ์œ„ํ•ด ๋”•์…”๋„ˆ๋ฆฌ ํ˜•ํƒœ๋กœ ์ €์žฅ
for _ in range(N):
    start, end = map(int, input().split()) # ์‚ฌ๋‹ค๋ฆฌ ์‹œ์ž‘ ์ง€์ , ๋ ์ง€์ 
    ladder[start] = end

for _ in range(M):
    start, end = map(int, input().split()) # ๋ฑ€ ์‹œ์ž‘ ์ง€์ , ๋ ์ง€์ 
    snake[start] = end

print(BFS())