2013-10-16 369 views
3

如果我們希望覆蓋搜索空間,好比說對所有三胞胎(x, y, z),其中xy,並且z1n之間,我們可以使用嵌套的循環,從而做到這一點:廣度第一次迭代?

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)等..

,並在那裏也爲一個名字算法會產生這樣的模式?

+0

我建議只使用實際的廣度優先搜索。從'(1,1,1)'開始,並且每當你出列'(x,y,z)'時,排列每個'(x + 1,y,z)','(x,y + 1,z )'和'(x,y,z + 1)',它們還沒有被排隊並且不會越過界限。 – user2357112

回答

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元組in int的特定情況,而不是任何數量的任何類型的集合。

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. 
+0

隊列沒有做任何事情。這與僅三個嵌套循環的「深度優先」迭代相同。 –