递归中德汉诺塔游戏代码?求助!
我又本书不过,输入时代码错误! 还又模板上要添加什么工具!留下什么字符!????、 --------------------编程问答-------------------- 完全听不懂 --------------------编程问答-------------------- 不懂,和题目一起看就更晕了 --------------------编程问答-------------------- 这样可能更好理解一些:
Dim count As Long
Sub HANNUOTA()
count = 0
MOVEALL 4, 4, "A", "B", "C"
End Sub
Sub MOVEALL(ByVal TOTAL As Long, ByVal N As Long, ByVal A As String, ByVal B As String, ByVal C As String)
If N = 1 Then
MOVEONE TOTAL, 1, A, C
Else
MOVEALL TOTAL, N - 1, A, C, B
MOVEONE TOTAL, N, A, C
MOVEALL TOTAL, N - 1, B, A, C
End If
End Sub
Sub MOVEONE(ByVal TOTAL As Long, ByVal N As Integer, ByVal X As String, ByVal Y As String)
count = count + 1
Debug.Print "STEP " & count & ": " & vbTab & " MOVE " & N & " FROM " & X & " TO " & Y
End Sub
返回:
STEP 1: MOVE 1 FROM A TO B
STEP 2: MOVE 2 FROM A TO C
STEP 3: MOVE 1 FROM B TO C
STEP 4: MOVE 3 FROM A TO B
STEP 5: MOVE 1 FROM C TO A
STEP 6: MOVE 2 FROM C TO B
STEP 7: MOVE 1 FROM A TO B
STEP 8: MOVE 4 FROM A TO C
STEP 9: MOVE 1 FROM B TO C
STEP 10: MOVE 2 FROM B TO A
STEP 11: MOVE 1 FROM C TO A
STEP 12: MOVE 3 FROM B TO C
STEP 13: MOVE 1 FROM A TO B
STEP 14: MOVE 2 FROM A TO C
STEP 15: MOVE 1 FROM B TO C
--------------------编程问答-------------------- 或者:
Sub HANNOI()
Const N = 4
ReDim arr(1 To 2 ^ N - 1)
Hanoi1 N, "A", "B", "C", 0, arr
MsgBox Join(arr, vbCrLf)
End Sub
Private Sub Hanoi1(ByVal N%, ByVal A$, ByVal B$, ByVal C$, ByRef q, ByRef arr())
'“A → C” 来代表把金片从A针移动到C针,即1阶汉诺塔问题的解
If N = 1 Then
q = q + 1: arr(q) = A & "→" & C '把金片n从A移动到C
Else
Hanoi1 N - 1, A, C, B, q, arr 'n-1个金片从A到B,以C为过渡
q = q + 1: arr(q) = A & "→" & C '把金片n从A移动到C
Hanoi1 N - 1, B, A, C, q, arr 'n-1个金片从B到C,以A为过渡
End If
End Sub
补充:VB , 基础类