Closed rygh4775 closed 5 years ago
하노이 타워 해결방법 if N == 3
하노이 탑 의사 코드
class Tower{
public :
stack<int> s;
int id;
Tower(int i) : id(i){}
void push(int disk){
s.push(disk);
}
int pop(){
if(s.size() == 0) return 0;
int disk = s.top();
s.pop();
return disk;
}
void print(){
while(s.empty() == false) {
int disk = pop();
cout << "disk : " << disk << endl;
}
}
void moveDisk(Tower * dest){
int disk = pop();
cout << "disk " << disk << " id : " << id << " to id : " << dest->id << endl;
if(disk > 0) {
dest->push(disk);
}
}
void moveDisks(int n, Tower* tower2, Tower* tower3) {
if (n <= 0) return;
moveDisks(n - 1,tower3, tower2);
moveDisk(tower2);
tower3->moveDisks(n - 1, tower2, this);
}
};
int main()
{
const int TowerCount = 3;
const int DiskCount = 3;
vector<Tower *> towers;
for (int i =0; i < TowerCount; i++){
towers.push_back(new Tower(i));
}
for(int i=1; i <= DiskCount; i++) {
towers[0]->push(i);
}
towers[0]->moveDisks(DiskCount, towers[2], towers[1]);
towers[2]->print();
return 0;
}
output :
disk 3 id : 0 to id : 2
disk 2 id : 0 to id : 1
disk 3 id : 2 to id : 1
disk 1 id : 0 to id : 2
disk 3 id : 1 to id : 0
disk 2 id : 1 to id : 2
disk 3 id : 0 to id : 2
disk : 3
disk : 2
disk : 1
Towers of Hanoi: In the classic problem of the Towers of Hanoi, you have 3 towers and N disks of different sizes which can slide onto any tower. The puzzle starts with disks sorted in ascending order of size from top to bottom (Le., each disk sits on top of an even larger one). You have the following constraints: (1) Only one disk can be moved at a time. (2) A disk is slid off the top of one tower onto another tower. (3) A disk cannot be placed on top of a smaller disk. Write a program to move the disks from the first tower to the last using Stacks.