go实现汉诺塔

喜欢而已 提交于 2019-12-16 21:08:46

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])
}

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!