hello-algo/codes/swift/chapter_divide_and_conquer/hanota.swift

59 lines
1.6 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* File: hanota.swift
* Created Time: 2023-09-02
* Author: nuomi1 (nuomi1@qq.com)
*/
/* */
func move(src: inout [Int], tar: inout [Int]) {
// src
let pan = src.popLast()!
// tar
tar.append(pan)
}
/* f(i) */
func dfs(i: Int, src: inout [Int], buf: inout [Int], tar: inout [Int]) {
// src tar
if i == 1 {
move(src: &src, tar: &tar)
return
}
// f(i-1) src i-1 tar buf
dfs(i: i - 1, src: &src, buf: &tar, tar: &buf)
// f(1) src tar
move(src: &src, tar: &tar)
// f(i-1) buf i-1 src tar
dfs(i: i - 1, src: &buf, buf: &src, tar: &tar)
}
/* */
func solveHanota(A: inout [Int], B: inout [Int], C: inout [Int]) {
let n = A.count
//
// src n B C
dfs(i: n, src: &A, buf: &B, tar: &C)
}
@main
enum Hanota {
/* Driver Code */
static func main() {
//
var A = [5, 4, 3, 2, 1]
var B: [Int] = []
var C: [Int] = []
print("初始状态下:")
print("A = \(A)")
print("B = \(B)")
print("C = \(C)")
solveHanota(A: &A, B: &B, C: &C)
print("圆盘移动完成后:")
print("A = \(A)")
print("B = \(B)")
print("C = \(C)")
}
}