倒酒问题!
大杯中有12L酒,现只有8L和5L的酒杯,问如何才能倒出6L的酒!?本人有一个利用递归解决问题的算法:
Option Explicit
Private Flags(12, 8, 5) As Byte
Private Direction(100, 1) As String * 1
Private Result(100, 2) As Byte
Private Bottle(2) As Byte
Private Lim(2) As Byte
Private Dir_Point As Byte, Result_Point As Byte
Private Action As Byte
Private A As Byte, B As Byte
Private Sub Form_Load()
Me.Show
Me.AutoRedraw = True
InitializeAll
Action = 0
Direction(0, 0) = "\"
Direction(0, 1) = "\"
StartRunning
Caption = Result_Point
End Sub
Private Sub Push_Result()
Dim I As Byte
For I = 0 To 2
Result(Result_Point, I) = Bottle(I)
Next I
Result_Point = Result_Point + 1
End Sub
Private Sub Push_Dir(From As Byte, Dest As Byte)
Direction(Dir_Point, 0) = Chr(From + Asc("A"))
Direction(Dir_Point, 1) = Chr(Dest + Asc("A"))
Dir_Point = Dir_Point + 1
End Sub
Private Sub InitializeAll()
Lim(0) = 12: Lim(1) = 8: Lim(2) = 5
Bottle(0) = 12: Bottle(1) = 0: Bottle(2) = 0
Dim I As Byte, J As Byte, K As Byte, L As Byte, M As Byte, N As Byte, O As Byte, R As Byte
For I = 0 To 12
For J = 0 To 8
For K = 0 To 5
Flags(I, J, K) = 0
Next K
Next J
Next I
For L = 1 To 100
For M = 0 To 1
Direction(L, M) = 0
Next M, L
For N = O To 100
For R = 0 To 2
Result(N, R) = 0
Next R, N
Dir_Point = 1
Result_Point = 0
End Sub
Private Sub DoPrint()
Dim I As Byte
Action = Action + 1
Print "Action"; Action
For I = 0 To Dir_Point - 1
Print Direction(I, 0); "->"; Direction(I, 1), Result(I, 0); "-"; Result(I, 1); "-"; Result(I, 2)
Next I
End Sub
Private Sub Countage(From As Byte, Dest As Byte)
On Error GoTo Endness
If Bottle(From) = 0 Then Exit Sub
If Bottle(Dest) = Lim(Dest) Then Exit Sub
A = Bottle(From): B = Bottle(Dest)
Bottle(Dest) = Bottle(Dest) + Bottle(From)
If Bottle(Dest) > Lim(Dest) Then
Bottle(From) = Bottle(Dest) - Lim(Dest)
Bottle(Dest) = Lim(Dest)
Else
Bottle(From) = 0
End If
If Flags(Bottle(0), Bottle(1), Bottle(2)) = 1 Then
Bottle(From) = A: Bottle(Dest) = B
Exit Sub
Else
Flags(Bottle(0), Bottle(1), Bottle(2)) = 1
End If
Push_Dir From, Dest
Push_Result
If Bottle(0) = 6 Or Bottle(1) = 6 Or Bottle(2) = 6 Then
DoPrint
Dir_Point = Dir_Point - 1
Result_Point = Result_Point - 1
Exit Sub
End If
'_________________________________核心________________________________
Countage 0, 1
Countage 1, 0
Countage 1, 2
Countage 2, 1
Countage 2, 0
Countage 0, 2
'_______________________________________________________________________
Exit Sub
Endness:
End
End Sub
Private Sub StartRunning()
Push_Result
Flags(12, 0, 0) = 1
Countage 0, 1
InitializeAll
Push_Result
Flags(12, 0, 0) = 1
Countage 0, 2
End Sub
不知有没有更简单的方法?
倒酒问题.rar
(1.9 KB)