hello-algo/codes/swift/chapter_divide_and_conquer/hanota.swift
Yudong Jin e720aa2d24
feat: Revised the book (#978)
* Sync recent changes to the revised Word.

* Revised the preface chapter

* Revised the introduction chapter

* Revised the computation complexity chapter

* Revised the chapter data structure

* Revised the chapter array and linked list

* Revised the chapter stack and queue

* Revised the chapter hashing

* Revised the chapter tree

* Revised the chapter heap

* Revised the chapter graph

* Revised the chapter searching

* Reivised the sorting chapter

* Revised the divide and conquer chapter

* Revised the chapter backtacking

* Revised the DP chapter

* Revised the greedy chapter

* Revised the appendix chapter

* Revised the preface chapter doubly

* Revised the figures
2023-12-02 06:21:34 +08:00

58 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)")
}
}