附:循环与递归汉诺塔算法性能比较的测试代码 Dim arr1, arr2, q Sub TestHanoi() Dim t1, t2, t3 Dim i% Const RunTimes = 100 Const N = 10 ‘N个金片需要的步骤数为2 ^ N – 1 ‘arr1存放递归算法结果,arr2存放循环算法计算的结果 ReDim arr1(1 To 2 ^ N - 1), arr2(1 To 2 ^ N - 1) t1 = Timer For i = 1 To RunTimes q = 0 Hanoi1 N, "A", "B", "C" Next i t2 = Timer For i = 1 To RunTimes q = 0 Hanoi2 N, "A", "B", "C" Next i t3 = Timer Debug.Print t2 - t1, t3 - t2 Range("A:B").ClearContents [a1].Resize(q, 1) = Application.Transpose(arr1) [b1].Resize(q, 1) = Application.Transpose(arr2) End Sub Private Sub Hanoi1(ByVal N%, ByVal A$, ByVal B$, ByVal C$) If N = 1 Then q = q + 1: arr1(q) = A & "→" & C Else Hanoi1 N - 1, A, C, B q = q + 1: arr1(q) = A & "→" & C Hanoi1 N - 1, B, A, C End If End Sub Private Sub Hanoi2(ByVal N%, ByVal A$, ByVal B$, ByVal C$) ‘根据递归代码写出的循环代码 Dim s$(1 To 3) Dim i%, j%, k%, m%, p%, qa% ReDim ia(1 To N), ja(1 To N), ka(1 To N), pa(1 To N) s(1) = A s(2) = B s(3) = C i = 1 j = 2 k = 3 p = N Do star: If p = 1 Then q = q + 1 arr2(q) = s(i) & "→" & s(k) If qa <= 0 Then Exit Do p = pa(qa) i = ia(qa) j = ja(qa) k = ka(qa) q = q + 1 arr2(q) = s(i) & "→" & s(k) qa = qa - 1 m = i i = j j = m GoTo star End If p = p - 1 qa = qa + 1 pa(qa) = p ia(qa) = i ja(qa) = j ka(qa) = k m = j j = k k = m Loop End Sub
[此贴子已经被作者于2007-1-29 21:20:34编辑过] |