Tower of Hanoi
//code by Soumyadeep Ghosh
//insta : @soumyadepp
//linked in: https://www.linkedin.com/in/soumyadeep-ghosh-90a1951b6/
#include <bits/stdc++.h>
using namespace std;
void toh(int n,char a,char b, char c)
{
if(n>0)
{
/*move n-1 disks from a to b using c*/
toh(n-1,a,c,b);
/*move a disc from a to c using b and display this step performed. Also note that a and c are different in the next called function*/
cout<<"Move a disk from "<<a<<" to "<<c<<endl;
toh(n-1,b,a,c);
}
}
int main()
{
int n;
cin>>n;
//names of the disks are a,b,c
toh(n,'a','b','c');
return 0;
}
//thank you!
0
0
def towerOfHanoi(N , source, destination, auxiliary):
if N==1:
print("Move disk 1 from source",source,"to destination",destination)
return
towerOfHanoi(N-1, source, auxiliary, destination)
print("Move disk",N,"from source",source,"to destination",destination)
towerOfHanoi(N-1, auxiliary, destination, source)
# Driver code
N = 3
towerOfHanoi(N,'A','B','C')
# A, C, B are the name of rods
Thank you!
0
0
4.5
8
/// find total number of steps
int towerOfHanoi(int n) {
/// pow(2,n)-1
if (n == 0) return 0;
return towerOfHanoi(n - 1) + 1 + towerOfHanoi(n - 1);
}
Thank you!
8
0
Are there any code examples left?
New code examples in category Python
-
Python 2023-04-11 03:04:20
-
Python 2022-03-27 22:40:04 pycharm no module named
-
Python 2022-03-27 22:25:05 assign multiple variablesin one line
-
Python 2022-03-27 22:20:02 levenshtein distance
-
Python 2022-03-27 21:35:09 get text from url python last slash
-
Python 2022-03-27 21:30:30 df concatenate df
-
Python 2022-03-27 21:25:09 python odd or even
-
Python 2022-03-27 21:15:32 python include function from another file
-
Python 2022-03-27 21:10:01 color module python
-
Python 2022-03-27 21:00:27 python tkinter cursor types