You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
hello-algo/codes/swift/chapter_divide_and_conquer/hanota.swift

59 lines
1.6 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

/**
* 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)")
}
}