我正在开发一个系统,可以完全探索这种性别的简单启发式地图(可以有不同数量的分支和不同的深度):
所以,我正在保存在地图深度大小的int数组中探索的位置。目标是探索地图的所有节点,以便输出:0 2 6, 0 2 7, 0 3 8, 0 3 9, 1 4 10 etc..
但实际上我的代码(需要多次调用,因为它只能更新一次数组),我有: 0 2 6, 0 2 7, 0 3 8, **1** 3 9, 1 4 10 etc..
这是我的代码,我不知道如何解决这个问题..
void get_next_branch(int *s, int nbr_branch, int size)
{
int a;
a = 0;
while (a < size)
{
condition = (size - a)/(nbr_branch - 1);
if (condition)
{
if (s[size - 1] % (condition) + 1 == condition)
s[a]++;
}
a++;
}
}
这是调用此函数的主要示例。
int main(void)
{
int id[3] = {0, 2, 6};
while (id[2] < 13)
{
printf("%d %d %d\n", id[0], id[1], id[2]);
get_next_branch(id, 2, 3);
}
return (0);
}
我提前谢谢你了!
答案 0 :(得分:1)
您可能希望对此问题使用封闭式公式
我们马上得到
深度 d = b d + 1
的节点数
(因为在深度0处我们已经有两个节点,所以没有使用#34; root&#34;节点。)
深度 d 的第一个节点的数量是较低级别的节点数的总和。基本上,
深度0 = 0的第一个节点编号
深度 d 的第一个节点编号&gt; 0 = b 1 + b 2 + b 3 + ... + b d
这是具有 b 之比的几何级数的总和。感谢公式(Wolfram)
深度的第一个节点编号 d = b *(1 - b d )/(1 - b)
E.g。 b == 2和 d == 2(3 rd 级别)
Number of nodes: 2 ^ 3 = 8
Starting at number: 2 * (1 - 2^2) / (1 - 2) = 6
可以从上面的公式中显示任何级别的树的程序。
使用 b 分支打印多个级别的树:
公用电源功能
int power(int n, int e) {
if (e < 1) return 1;
int p=n;
while (--e) p *= n;
return p;
}
上面的两个公式
int nodes_at_depth(int branches, int depth) {
return power(branches, depth+1);
}
int first_at_depth(int branches, int depth) {
return (branches * (1 - power(branches, depth))) / (1 - branches);
}
示例主程序,名为
./heuristic nb_of_branches nb_of_levels
调用两个函数
int main(int argc, char **argv)
{
if (argc != 3) return 1;
int b = atoi(*++argv);
int d = atoi(*++argv);
if (b < 2) return 2;
int i,j;
for (i=0 ; i<d ; i++) {
int n = nodes_at_depth(b, i); // number of nodes at level i
int s = first_at_depth(b, i); // first number at that level
for (j=0 ; j<n ; j++) printf(" %d", s+j);
printf("\n");
}
return 0;
}
调用
./heuristic 2 4
给出
0 1
2 3 4 5
6 7 8 9 10 11 12 13
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29