forked from jyx-fyh/algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhanoi.cpp
More file actions
62 lines (58 loc) · 1.05 KB
/
hanoi.cpp
File metadata and controls
62 lines (58 loc) · 1.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
//
// Created by ButcherX on 23-11-17.
//
#include<iostream>
#include<string>
using std::string;
void moveToRelay(int n);
void moveToDestination(int n)
{
if(n == 1)
{
std::cout<< "move to Destination" << std::endl;
return;
}
moveToRelay(n-1);
moveToDestination(1);
moveToDestination(n-1);
}
void moveToRelay(int n)
{
if(n == 1)
{
std::cout<< "move to Relay" << std::endl;
return;
}
moveToDestination(n - 1);
moveToRelay(1);
moveToRelay(n-1);
}
void hanoi(int n)
{
moveToRelay(n - 1);
moveToDestination(1);
moveToDestination(n-1);
}
//=================================
void move(int n, char from, char to)
{
if(n == 1)
{
std::cout <<"move from " << from << " to " << to << std::endl;
return;
}
char other = 'b' - (from-'b') - (to-'b');
move(n - 1, from, other);
move(1, from, to);
move(n - 1, other, to);
}
void hanoi1(int n)
{
move(n - 1, 'a', 'b');
move(1, 'a', 'c');
move(n - 1, 'b', 'c');
}
int main()
{
hanoi1(3);
}