Non-recursive algorithm:
Determine the order of the pillars according to the number of discs:
If n is even, A B C is placed in a clockwise direction;
If n is odd, A C B is placed in a clockwise direction.
Then do the following:
(1) in the clockwise direction of the disk 1 from the current column to the next column, that is, when n is even, if the disk 1 in column A, then move it to B; If the disk 1 is in column B, move it to C; If the disk 1 is in column C, move it to a.
(2) Next, move the movable discs of the other two pillars to the new pillars. That is, the disk on the non-empty pillar is moved to the empty column, when the two pillars are non-empty, move the smaller disc.
(3) repeated (1) (2) operation, finally can be completed according to the provisions of the Hanoi movement.
C + + implementation:
#include <bits/stdc++.h>using namespacestd;typedef unsignedLong LongLL;structhanoi{intN; structTower {CharName; Stack<int>Disks; }tow[3]; voidInitintnum) {N=num; for(intI=0;i<3; i++) {Tow[i]. Name='A'+i; while(!Tow[i]. Disks.empty ()) Tow[i]. Disks.pop (); } for(inti=n;i>=1; i--) tow[0]. Disks.push (i); } voidsolve () {LL cnt=0, cnt_max= (1<<n)-1; while(cnt<Cnt_max) {CNT++; intFlag1,flag2; if(cnt%2)//the movement of the odd number of times { for(intI=0;i<3; i++)if(! Tow[i]. Disks.empty () && tow[i]. Disks.top () = =1) flag1=i; if(n%2)//N is an odd numberFlag2= ((flag1-1)+3)%3; ElseFlag2= (flag1+1)%3; } Else//the movement of an even number of times{Flag1=flag2=-1; for(intI=0;i<3; i++) { if(! Tow[i]. Disks.empty () && tow[i]. Disks.top () = =1)Continue; if(flag1==-1) flag1=i; Else if(flag2==-1) flag2=i; } if(! TOW[FLAG1]. Disks.empty () &&!Tow[flag2]. Disks.empty ()) {if(Tow[flag1]. Disks.top () >Tow[flag2]. Disks.top ()) swap (FLAG1,FLAG2); } Else { if(Tow[flag1]. Disks.empty ()) swap (FLAG1,FLAG2); }} cout<<cnt<<": "<<"Move Disk"<<TOW[FLAG1]. Disks.top () <<" from"<<TOW[FLAG1]. name<<" to"<<TOW[FLAG2]. name<<Endl; TOW[FLAG2]. Disks.push (Tow[flag1]. Disks.top ()); TOW[FLAG1]. Disks.pop (); }}}hanoi;intMain () {intN; cout<<"number of input discs:"; Cin>>N; Hanoi.init (n); Hanoi.solve ();}
Recursive algorithm:
The Hanoi (N,A,C,B) means that the N discs are moved on a column by following several steps of the Hanoi rule, and all are moved to the C column in the original order with the aid of the B-pillar;
#include <bits/stdc++.h>using namespacestd;typedef unsignedLong LongLL; LL CNT;voidHanoi (intNCharACharCCharb) { if(n==1) {cout<<++cnt<<": "<<"Move Disk"<<n<<" from"<<a<<" to"<<c<<Endl; return; } Hanoi (n-1, A,b,c); cout<<++cnt<<": "<<"Move Disk"<<n<<" from"<<a<<" to"<<c<<Endl; Hanoi (n-1, B,c,a); return;}intMain () {intN; cout<<"number of input discs:"; CIN>>N; CNT=0; Hanoi (N,'A','C','B');}
Recursive algorithm and non-recursive algorithm of the tower of Hanoi Hanoi problem