static bool countNeighbor3D(Point3D_int p, int branch_max) { int i; int count = 0; Point3D_int p3; for (i = 0; i < D3; i++) { p3.x = p.x + dx[i]; p3.y = p.y + dy[i]; p3.z = p.z + dz[i]; if (inBound3D(p3) && !isEmpty3D(p3)) { count++; } } return(count < branch_max); }
//branch_max表示路径的交叉点处的最多连接多少个节点,至少为2,数值越大,分支越多 static void search3D(int branch_max) { int i, j; int[] r = new int[D3]; Random rand = new Random(); Stack <Point3D_int> s = new Stack <Point3D_int>(); Point3D_int p, p3; p.x = 0; p.y = 0; p.z = 0; s.Push(p); while (s.Count > 0) { p = s.Pop(); if (isEmpty3D(p) && countNeighbor3D(p, branch_max)) { map3D[p.x, p.y, p.z] = 1; for (j = 0; j < D3; j++)//重置随机方向数组,令到数组的值为从0至D3-1 { r[j] = j; } for (i = D3; i > 0; i--) //随机方向数组的大小从D3开始递减至0 { j = rand.Next() % i; //每次从随机方向数组取一个方向索引j (j>=0&&j<=i-1) p3 = new Point3D_int(); p3.x = p.x + dx[r[j]]; p3.y = p.y + dy[r[j]]; p3.z = p.z + dz[r[j]]; if (j != i - 1)//如果j不是随机方向数组的最后一个元素,则将最后一个元素i-1保存到位置j { r[j] = r[i - 1]; } if (inBound3D(p3) && isEmpty3D(p3) && countNeighbor3D(p3, branch_max)) { s.Push(p3); } } } } }
static bool isEmpty3D(Point3D_int p) { return(map3D[p.x, p.y, p.z] == 0); }
static bool inBound3D(Point3D_int p) { return(p.x >= 0 && p.x < xmax && p.y >= 0 && p.y < ymax && p.z >= 0 && p.z < zmax); }