Skip to content

Instantly share code, notes, and snippets.

@rickyzhang-cn
Created October 20, 2014 13:30
Show Gist options
  • Select an option

  • Save rickyzhang-cn/eea71d1142ebc7717c04 to your computer and use it in GitHub Desktop.

Select an option

Save rickyzhang-cn/eea71d1142ebc7717c04 to your computer and use it in GitHub Desktop.
汉诺塔问题的递归和非递归实现
#include <iostream>
using namespace std;
void hanoi(int n, char src, char bri, char dst)
{
if(n == 1)
{
cout<<"Move"<<n<<"from"<<src<<"to"<<dst<<endl;
}else
{
hanoi(n-1,src,dst,bri);
cout<<"Move"<<n<<"from"<<src<<"to"<<dst<<endl;
hanoi(n-1,bri,src,dst);
}
}
int main()
{
int n;
cout<<"Input the number n:";
cin>>n;
hanoi(n,'A','B','C');
return 0;
}
#include <iostream>
#include <stack>
using namespace std;
struct hanoi_record {
int begin, end;
char src, bri, dst;
hanoi_record() {}
hanoi_record(int pbegin, int pend, char psrc, char pbri, char pdst):
begin(pbegin), end(pend), src(psrc), bri(pbri), dst(pdst) {}
};
void hanoi_stack(int begin, int end, char src, char bri, char dst)
{
stack<hanoi_record> hr;
hanoi_record r(begin,end,src,bri,dst);
hr.push(r);
while(!hr.empty())
{
hanoi_record temp;
temp=hr.top();
hr.pop();
if(temp.begin != temp.end)
{
hr.push(hanoi_record(temp.begin,temp.end-1,temp.bri,temp.src,temp.dst));
hr.push(hanoi_record(temp.end,temp.end,temp.src,temp.bri,temp.dst));
hr.push(hanoi_record(temp.begin,temp.end-1,temp.src,temp.dst,temp.bri));
}else
{
cout<<"Move"<<temp.begin<<"from"<<temp.src<<"to"<<temp.dst<<endl;
}
}
}
int main()
{
int n;
cout<<"Input the number n:";
cin>>n;
hanoi_stack(1,n,'A','B','C');
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment