[SWEA] 5247 연산

O2o2✨·2020년 11월 15일
0

알고리즘

목록 보기
4/43

문제 링크: 5247. [파이썬 S/W 문제해결 구현] 6일차 - 연산

from collections import deque

for test_case in range(1, int(input())+1):
    n, m = map(int, input().split())

    q = deque([(n, 0)])
    visited = set()
    visited.add(n)

    while q:
        n, cnt = q.popleft()
        if n == m:
            break

        if n + 1 not in visited and n + 1 <= 1000000:
            q.append((n + 1, cnt + 1))
            visited.add(n + 1)
        if n - 1 not in visited and n - 1 <= 1000000:
            q.append((n - 1, cnt + 1))
            visited.add(n - 1)
        if n * 2 not in visited and n * 2 <= 1000000:
            q.append((n * 2, cnt + 1))
            visited.add(n * 2)
        if n - 10 not in visited and n - 10 <= 1000000:
            q.append((n - 10, cnt + 1))
            visited.add(n - 10)

    print(f'#{test_case} {cnt}')
profile
프론트엔드 & 퍼블리셔

0개의 댓글