|
用递归编了一个汉诺塔演示程序,程序写的比较简单,欢迎讨论。
- Public m&, a(), b(), c() 'm金片数,及a,b,c金片数组
- '主程序 (By 风中浮云)
- Sub MainPrg()
- n = [f1].Value '修改金片数(10以内)
- m = n
-
- ReDim a(1 To n)
- ReDim b(1 To n)
- ReDim c(1 To n)
-
- For i = n To 1 Step -1
- a(n + 1 - i) = i
- Next
- Range("a1:c10").ClearContents
-
- Call dispArr
- Call hannuo(n, "A", "B", "C")
-
- MsgBox "OK"
- End Sub
- '汉诺塔算法基本框架
- Sub hannuo(n, p1, p2, p3)
- If n = 1 Then
- Call MoveIt(p1, p3) '只有1块金片时直接从p1移到p3
- Exit Sub
- Else
- Call hannuo(n - 1, p1, p3, p2) '将n-1个金片从p1移到p2
- Call MoveIt(p1, p3) '将n号金片从p1移到p3
- Call hannuo(n - 1, p2, p1, p3) '将n-1个金片从p2移到p3
- End If
- End Sub
- '移动两块金片x,y
- Sub MoveIt(x, y)
- Debug.Print x & "--->" & y
-
- '根据移动对象修改对应数组,分6种情况处理
- j = 0: k = 0
- If x = "A" And y = "B" Then '如果移动A柱金片到B柱
- For i = 1 To m '扫描a,b数组最后一块金片的位置
- If a(i) > 0 Then j = j + 1
- If b(i) > 0 Then k = k + 1
- Next
- tmp = a(j)
- a(j) = Null 'a数组拿掉最后一块金片
- b(k + 1) = tmp 'b数组增加一块金片
- End If
-
- If x = "A" And y = "C" Then
- For i = 1 To m
- If a(i) > 0 Then j = j + 1
- If c(i) > 0 Then k = k + 1
- Next
- tmp = a(j)
- a(j) = Null
- c(k + 1) = tmp
- End If
-
- If x = "B" And y = "C" Then
- For i = 1 To m
- If b(i) > 0 Then j = j + 1
- If c(i) > 0 Then k = k + 1
- Next
- tmp = b(j)
- b(j) = Null
- c(k + 1) = tmp
- End If
- If x = "B" And y = "A" Then
- For i = 1 To m
- If b(i) > 0 Then j = j + 1
- If a(i) > 0 Then k = k + 1
- Next
- tmp = b(j)
- b(j) = Null
- a(k + 1) = tmp
- End If
- If x = "C" And y = "A" Then
- For i = 1 To m
- If c(i) > 0 Then j = j + 1
- If a(i) > 0 Then k = k + 1
- Next
- tmp = c(j)
- c(j) = Null
- a(k + 1) = tmp
- End If
-
- If x = "C" And y = "B" Then
- For i = 1 To m
- If c(i) > 0 Then j = j + 1
- If b(i) > 0 Then k = k + 1
- Next
- tmp = c(j)
- c(j) = Null
- b(k + 1) = tmp
- End If
-
- Call dispArr '移动完毕显示当前状态
- End Sub
- '显示当前状态
- Sub dispArr()
- For i = 1 To 3
- For j = 1 To m
- Cells(11 - j, 1).Value = a(j)
- Cells(11 - j, 2).Value = b(j)
- Cells(11 - j, 3).Value = c(j)
- Next
- Next
- End Sub
复制代码
|
|