λ³Έλ¬Έ λ°”λ‘œκ°€κΈ°
πŸƒ algorithm/boj

BOJ 1963 - μ†Œμˆ˜ 경둜

by HandHand 2021. 3. 18.

문제

λ°±μ€€ 온라인 저지 - 1963번

풀이 κ³Όμ •

λͺ©ν‘œ 지점에 λ„λ‹¬ν•˜κΈ° μœ„ν•œ μ΅œλ‹¨ 경둜λ₯Ό κ΅¬ν•˜λŠ” λ¬Έμ œμ΄λ―€λ‘œ BFS λ₯Ό 톡해 닡을 κ΅¬ν–ˆμŠ΅λ‹ˆλ‹€.

μš°μ„  ν˜„μž¬ μˆ«μžμ—μ„œ λ³€κ²½ κ°€λŠ₯ν•œ μžλ¦¬μˆ˜λŠ” 총 4κ°œμ΄λ―€λ‘œ 각 μžλ¦¬μˆ˜μ— 0~9의 숫자λ₯Ό ν•˜λ‚˜μ”© 넣어보며
그둜 인해 μƒμ„±λœ μˆ«μžκ°€ μ†Œμˆ˜μΌ 경우 큐에 λ„£μ–΄μ€¬μŠ΅λ‹ˆλ‹€.
μ΄λ•Œ μ†Œμˆ˜μΈμ§€ νŒλ³„ν•˜λŠ” μ•Œκ³ λ¦¬μ¦˜μ€ O(root(N)) 의 μ‹œκ°„ λ³΅μž‘λ„λ₯Ό κ°€μ§€λ―€λ‘œ 주어진 μ œν•œ μ‹œκ°„λ‚΄μ— μΆ©λΆ„νžˆ μˆ˜ν–‰ κ°€λŠ₯ν•©λ‹ˆλ‹€.

μ½”λ“œ


import sys
from collections import deque


def is_prime(n):
    if n <= 1:
        return False
    if n == 2:
        return True

    if n % 2 == 0:
        return False

    sqrtn = int(n**0.5)
    for div in range(3, sqrtn+1, 2):
        if n % div == 0:
            return False

    return True


def bfs(start, goal):
    q = deque()
    visit = [0 for _ in range(10000)]

    q.append((start, 0))
    visit[start] = 1

    while q:
        here, cost = q.popleft()
        if here == goal:
            return cost

        temp = str(here)
        for idx, digit in enumerate(temp):

            for n in range(10):
                if n != int(digit):
                    new = temp[:idx] + str(n) + temp[idx+1:]
                    if is_prime(int(new)) and not visit[int(new)]:
                        q.append((int(new), cost + 1))
                        visit[int(new)] = 1

    return 'Impossible'


if __name__ == '__main__':
    T = int(input())
    for case in range(T):
        frm, to = list(map(int, sys.stdin.readline().split()))
        ret = bfs(frm, to)
        print(ret)
λ°˜μ‘ν˜•

'πŸƒ algorithm > boj' μΉ΄ν…Œκ³ λ¦¬μ˜ λ‹€λ₯Έ κΈ€

BOJ 16397 - νƒˆμΆœ  (0) 2021.03.18
BOJ 2563 - 색쒅이  (0) 2021.03.18
BOJ 4195 - 친ꡬ λ„€νŠΈμ›Œν¬  (0) 2021.03.18
BOJ 17626 - Four Squares  (0) 2021.03.18
BOJ 1303 - μ „μŸ - μ „νˆ¬  (0) 2021.03.18

πŸ’¬ λŒ“κΈ€