我想用标准的Hanoi Towers algorythm编写,使用3根杆和n张光盘。但是我也想学习如何使用列表,所以我想我可以将它结合起来。
我想过创造3个元素,每个元素代表单个棒。它们中的每一个都有discs[]
数组,例如,如果一个棒将有5个光盘,则该数组将包含[1, 2, 3, 4, 5]
元素。
好的,我实施了结构等,但我的问题是 - 如何实际解决河内塔迭代?
可以直接绕过杆,对于每个盘检查它可以去哪里,并将其移动到第一个检查位置 - 然后重复循环?
答案 0 :(得分:4)
无需使用列表过度复杂化您的生活。使用数组。
#include <stdio.h>
#define DISKS 4 // 10 max
int stacks[3][DISKS];
int sps[3];
void init(int from)
{
int i;
sps[2] = sps[1] = sps[0] = 0;
for (i = 0; i < DISKS; i++)
stacks[from][i] = DISKS - i; // disk radius
sps[from] = DISKS;
}
void print(void)
{
int i, j, k;
for (i = DISKS - 1; i >= 0; i--)
{
for (j = 0; j < 3; j++)
{
if (sps[j] > i)
{
for (k = 0; k < 10 - stacks[j][i]; k++)
printf(" ");
for (k = 0; k < 2 * stacks[j][i]; k++)
printf("x");
for (k = 0; k < 10 - stacks[j][i]; k++)
printf(" ");
}
else
{
printf(" "); // 10 * 2
}
printf(" ");
}
printf("\n");
}
printf("_________/\\_________ _________/\\_________ _________/\\_________\n\n");
}
void solve(int to, int from, int cnt)
{
int other = from ^ to ^ 3;
if (!cnt) return;
solve(other, from, cnt - 1);
stacks[to][sps[to]++] = stacks[from][--sps[from]];
print();
solve(to, other, cnt - 1);
}
int main(void)
{
init(0);
print();
solve(2, 0, DISKS);
return 0;
}
输出(ideone):
xx
xxxx
xxxxxx
xxxxxxxx
_________/\_________ _________/\_________ _________/\_________
xxxx
xxxxxx
xxxxxxxx xx
_________/\_________ _________/\_________ _________/\_________
xxxxxx
xxxxxxxx xx xxxx
_________/\_________ _________/\_________ _________/\_________
xxxxxx xx
xxxxxxxx xxxx
_________/\_________ _________/\_________ _________/\_________
xx
xxxxxxxx xxxxxx xxxx
_________/\_________ _________/\_________ _________/\_________
xx
xxxxxxxx xxxxxx xxxx
_________/\_________ _________/\_________ _________/\_________
xx xxxx
xxxxxxxx xxxxxx
_________/\_________ _________/\_________ _________/\_________
xx
xxxx
xxxxxxxx xxxxxx
_________/\_________ _________/\_________ _________/\_________
xx
xxxx
xxxxxx xxxxxxxx
_________/\_________ _________/\_________ _________/\_________
xxxx xx
xxxxxx xxxxxxxx
_________/\_________ _________/\_________ _________/\_________
xx
xxxx xxxxxx xxxxxxxx
_________/\_________ _________/\_________ _________/\_________
xx
xxxx xxxxxx xxxxxxxx
_________/\_________ _________/\_________ _________/\_________
xx xxxxxx
xxxx xxxxxxxx
_________/\_________ _________/\_________ _________/\_________
xxxxxx
xxxx xx xxxxxxxx
_________/\_________ _________/\_________ _________/\_________
xxxx
xxxxxx
xx xxxxxxxx
_________/\_________ _________/\_________ _________/\_________
xx
xxxx
xxxxxx
xxxxxxxx
_________/\_________ _________/\_________ _________/\_________