쥐수의 공부노트

백준 11729번 하노이 탑 이동 순서 본문

swift 알고리즘/재귀

백준 11729번 하노이 탑 이동 순서

쥐수 2023. 7. 11. 16:01
728x90

정답 :

import Foundation

let num = Int(readLine()!)!
let result = pow(2, num) - 1

func move(from: Int, to : Int) {
    print("\(from) \(to)")
}

func hanoi(n : Int, from : Int, by : Int , to : Int) {
    if n == 1 {
        move(from: from, to: to)
    }
    else {
        hanoi(n: n-1, from: from, by: to, to: by)
        move(from: from, to: to)
        hanoi(n: n-1, from: by, by: from, to: to)
    }
}
print(result)
hanoi(n: num, from: 1, by: 2, to: 3)
더보기

TMI : 하노이탑 알고리즘에 대해 공부하자! 

728x90