[Classic topic] Tower of Hanoi

( Search by yourself )

 

No disk can be enlarged on the small disk, and only one disk can be moved at a time between the three pillars. What should I do?

Idea: We assume that n-1 disks have been placed in the middle tower, then the nth one is placed on the target tower, and then similarly, n-1 disks can be placed on the target tower.

It obviously is a recursive structure problem

Recursive solution:

 #include<bits/stdc++.h>
using namespace std;
void Hanoi(int n,char s,char m,char t){
	if(n==1){cout<<s<<"->"<<t<<endl;return;}
	Hanoi(n-1,s,t,m);
	cout<<s<<"->"<<t<<endl;
	Hanoi(n-1,m,s,t);
}
int main(){
	int n;cin>>n;
	char a,b,c;
	cin>>a>>b>>c;
	Hanoi(n,a,b,c);
	return 0;
}

 

Guess you like

Origin blog.csdn.net/melon_sama/article/details/108405531