go实现汉诺塔
package main import ( "flag" "fmt" "strconv" ) var num int // 可输入汉诺塔层数 var Hanoi [3][]int var disks int = 0 func init() { flag.IntVar(&num, "num", 100, "The greeting object.") } func main() { flag.Parse() if (num <= 0) { fmt.Printf("%v \n", "参数必须大于0") return } for i := num; i > 0; i-- { Hanoi[0] = append(Hanoi[0], i) } echo() hanoi(num, 0, 1, 2) } func move( from int, to int) { disks++ length := len(Hanoi[from]) Hanoi[to] = append(Hanoi[to], Hanoi[from][length-1]) Hanoi[from] = append(Hanoi[from][:length-1]) echo() } func hanoi(n int, A int, B int, C int) { if (n == 1) { move( A, C); } else { hanoi(n-1, A, C, B); move(A, C); hanoi(n-1, B, A, C); } } func echo() { fmt.Printf("移动第"+strconv.Itoa(disks)+"步:%v \n", "----------------------------------") fmt.Printf("塔A:%v \n", Hanoi[0]) fmt.Printf("塔B:%v \n", Hanoi[1]) fmt.Printf("塔C:%v \n", Hanoi[2]) }
来源:https://www.cnblogs.com/lijian-switch/p/11959076.html