하노이 탑 코드
//재귀 함수와 비재귀 함수 버전
#include <iostream>
#include <stack>
using namespace std;
void move(int no, int x=1, int y=3){
if(no>1)
move(no-1,x,6-x-y);
cout<<"원반["<<no<<"]를(을) "<<(char)('A'+x-1)<<"기둥에서 "<<(char)('A'+y-1)<<"기둥으로 옮김.\n";
if(no>1)
move(no-1,6-x-y,y);
}
void move1(int no, int x=1, int y=3){
stack<int> s;
while(1){
while(no>1){
s.push(no),s.push(x),s.push(y);
no=no-1,y=6-x-y;
}
cout<<"원반["<<no<<"]를(을) "<<(char)('A'+x-1)<<"기둥에서 "<<(char)('A'+y-1)<<"기둥으로 옮김.\n";
if(s.size()){
y=s.top(),s.pop();
x=s.top(),s.pop();
no=s.top(),s.pop();
cout<<"원반["<<no<<"]를(을) "<<(char)('A'+x-1)<<"기둥에서 "<<(char)('A'+y-1)<<"기둥으로 옮김.\n";
no=no-1,x=6-x-y;
}
else
break;
}
}
int main() {
// your code goes here
cout<<"재귀 버전\n";
move(4);
cout<<"비재귀 버전\n";
move1(4);
return 0;
}
'C,C++ 코드' 카테고리의 다른 글
일반템 스타포스 시뮬 (0) | 2018.12.29 |
---|---|
single linked list (0) | 2018.12.25 |
인라인 코드 테스트 (2) | 2018.12.22 |
진자 운동 코드 (0) | 2018.12.22 |
퀵 정렬 함수 (0) | 2018.12.16 |