프로그래밍/문제풀이

[BOJ]14395 4연산 Python 풀이

Cycrypt0 2023. 4. 10. 23:05
728x90
from collections import deque
s, t = map(int, input().split())
MAX = 10e9
def BFS():
    visited = set()
    q = deque()
    q.append((s, ''))
    operator = ['*', '+', '/']
    result = -1
    if s == t:
        return 0
    
    while q:
        node, op = q.popleft()
        
        if node == t:
            result = op
            break
        for o in operator:
            calc = eval(str(node) + o + str(node))
            if 0 <= node <= MAX and calc not in visited:
                q.append((calc, op+o))
                visited.add(calc)
    return result

print(BFS())

어차피 빼기 해봐야 0이 나와버리므로 연산자에서 빼고

나누기 해봐야 1이 나오므로..

연산자 우선순위에 맞게 풀이하였음.

eval을 이용하여 string을 연산하였고 나머지는 BFS를 이용하였음

728x90