1.递归算法:
程序代码:
void move(char x,char y)
{
static int count = 0;
printf("%c -> %c",x,y);
count++;
if(count == 4)
{
printf("\n");
count = 0;
}
else
printf("\t");
}
void hanio(int n,char x,char y,char z)
//把n个圆盘从塔座X移动到塔座Z的过程,Y为辅助塔座
{
if(n <= 0 )
return;
if(n == 1)
{
move(x,z);
return;
}
hanio(n-1,x,z,y);
move(x,z)
hanio(n-1,y,x,z);
}
时间复杂度:移动n个盘子相当于移动两次n-1个盘子的时间,由数学归纳法可得该算法的时间代价为O(2n)。
空间复杂度:主要用于实现递归的栈,深度为n,故空间代价为O(n)。
2.非递归算法:
数据结构:
typedef struct
{
int n; //问题规模
char x; //起始塔座
char y; //辅助塔座
char z; //目标塔座
}DataType;
程序代码:
void hanio_nonrecursive(int n,char x,char y,char z)
{
PSeqStack ps;
DataType temp,temp2'
if(n<=0)
return;
if(n == 1)
{
move(x,z);
return;
}
ps = createEmptyStack_seq();
temp.n = n; temp.x = x; temp.y = y; temp.z = z;
push_seq(ps,temp); //初状态进栈
while(!isEmptyStack_seq(ps))
{
temp2 = top_seq(ps);
pop_seq(ps);
if(temp2.n == 1)
move(temp2.x,temp2.z);
else
{
temp.n = temp2.n-1; temp.x = temp2.y; temp.y = temp2.x; temp.z = temp2.z;
push_seq(ps,temp); //(n-1,y,x,z)进栈
temp.n = 1; temp.x = temp2.x; temp.y = temp2.y; temp.z = temp2.z;
push_seq(ps,temp); //(1,x,y,z)进栈
temp.n = temp2.n-1; temp.x = temp2.x; temp.y = temp2.z; temp.z = temp2.y;
push_seq(ps,temp); //(n-1,x,z,y)进栈
}
}
free(ps);
}
代价分析:非递归的代价不会超过递归算法的代价。