λ¬Έμ
λ°±μ€ μ¨λΌμΈ μ μ§ - 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 |
π¬ λκΈ