카테고리 없음

[프로그래머스] 하노이의탑 (python) 미완

박수련 2024. 3. 29. 14:09

문제 설명

 

위 조건을 만족하는 하노이의 탑을 쌓을 때 원판을 옮기는 최소 방법을 구하는 문제

접근

먼저 직접 하노이의 탑을 쌓아보니 가장 처음 1번 원판을 옮길 때, n이 홀수라면  3번 기둥 짝수라면  2번 기둥에 쌓아야 최소 횟수로 하노이의 탑을 옮길 수 있다. 

그리고 조건문을 통해 옮기려는 원판보다 작은 원판이 있거나, 같은 홀수 또는 짝수일 때는 옮기지 못하도록 설정해주었다.

3번 기둥을 조건문의 가장 앞쪽에 두어 3번이 가장 우선순위가 되도록 설정했다. 

 

시간 부족으로 코드를 완성하지 못했다..

코드

def solution(n):
    answer = []
    hanoi = [[], [i for i in range(n, 0, -1)], [], []]

    # 1번 원판 옮기기
    if n % 2 == 0:
        answer.append([1, 2])
        hanoi[1].pop()
        hanoi[2].append(1)
    else:
        answer.append([1, 3])
        hanoi[1].pop()
        hanoi[3].append(1)

    cir = 2
    while True:
        # 현재 옮기려고 하는 원판이 위치하는 기둥 번호찾기
        for i in range(1, 4):
            if cir in hanoi[i]:
                srt = i
                break

        if len(hanoi[srt]) == 0 or hanoi[srt][-1] != cir:
            cir += 1
            continue

        if srt != 3 and (
            len(hanoi[3]) == 0 or (hanoi[3][-1] > cir and hanoi[3][-1] % 2 != cir % 2)
        ):
            answer.append([srt, 3])
            hanoi[srt].pop()
            hanoi[3].append(cir)
            print(33, end="")

        elif srt != 2 and (
            len(hanoi[2]) == 0 or (hanoi[2][-1] > cir and hanoi[2][-1] % 2 != cir % 2)
        ):
            print(len(hanoi[2]))
            if len(hanoi[2]) == 0 or (
                hanoi[2][-1] > cir and hanoi[2][-1] % 2 != cir % 2
            ):
                answer.append([srt, 2])
                hanoi[srt].pop()
                hanoi[2].append(cir)
                print(22, end="")

        elif srt != 1 and (
            len(hanoi[1]) == 0 or (hanoi[1][-1] > cir and hanoi[1][-1] % 2 != cir % 2)
        ):
            answer.append([srt, 1])
            hanoi[srt].pop()
            hanoi[1].append(cir)


        if cir == 1 and len(hanoi[3]) == n:
            break

        cir += 1

        if cir == n + 1:
            cir = 1


    return answer