广度优先遍历?

3
如果我们想要覆盖一个搜索空间,比如说所有三元组 (x, y, z),其中 xyz 的值在 1n 之间,我们可以使用嵌套循环来实现:
for (int x = 1; x <= n; x++)
   for (int y = 1; y <= n; y++)
      for (int z = 1; z <= n; z++)

这将生成三元组:(1, 1, 1)(1, 1, 2)(1, 1, 3)(1, 1, 4) 等等,实际上是“深度优先搜索”或深度优先迭代。
有没有一种以更“广度优先”的方式进行迭代的方法?这样的迭代将以类似于以下顺序生成三元组: (1, 1, 1)(2, 1, 1)(1, 2, 1)(1, 1, 2)(2, 2, 1)(2, 1, 2)(1, 2, 2)(2, 2, 2)(3, 1, 1) 等等。
这个算法的名称是什么?

我建议直接使用实际的广度优先搜索。从(1, 1, 1)开始,每当你出队(x, y, z)时,将尚未入队且不超过边界的(x+1, y, z)(x, y+1, z)(x, y, z+1)都入队。 - user2357112
2个回答

0
这段C#代码可以生成我描述的图案,并且顺序良好,但我感觉有更好的方法来实现它。
void Visit(ISet<Tuple<int, int, int>> pSet, int pX, int pY, int pZ) {
   var value = Tuple.Create(pX, pY, pZ);
   if (pSet == null)
      Console.WriteLine(value);
   else if (!pSet.Contains(value)){
      pSet.Add(value);
      Console.WriteLine(value);
   }
}

void Iterate() {
   const int n = 5;
   for (int x = 1; x <= n; x++) {
      var set = new HashSet<Tuple<int, int, int>>();
      for (int y = 1; y <= x; y++)
         for (int z = 1; z <= y; z++) {
            Visit(set, z, y, x);
            Visit(set, z, x, y);
            Visit(set, y, z, x);
            Visit(set, y, x, z);
            Visit(set, x, z, y);
            Visit(set, x, y, z);
         }
   }
}

这段代码生成模式而不维护任何列表或进行任何冲突检查。我已确认它生成n³个元组,没有重复项(最多n=500)。唯一的问题是,它仅适用于迭代整数3元组的特定情况,而不是任何类型集合的任意数量。

static void Iterate() {
   const int n = 500;
   for (int x = 1; x <= n; x++) {
      for (int y = 1; y <= x; y++)
         for (int z = 1; z <= y; z++) {
            Visit(z, y, x);
            if (x == y && y == z && x == z)
               continue;

            if (x != y)
               Visit(z, x, y);

            if (z != y) {
               Visit(y, z, x);
               Visit(y, x, z);
            }

            if (x != y && x != z) {
               Visit(x, z, y);
               if (z != y)
                  Visit(x, y, z);
            }
         }
   }
}

-1
This should work.  
        for (int x = 1; x <= n; x++)
           for (int y = 1; y <= n; y++)
              {
               for (int z = 1; z <= n; z++)
                {  
                  enqueue(the x-y-z triplet);
                }
                  print(till the queue empties);
                }
Sorry for my pseudo-C.

队列没有做任何事情。这与只有三个嵌套循环的“深度优先”迭代完全相同。 - Dave Cousineau

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接