2011-07-28 34 views
2

我試圖使用flood fill算法來查找列表中所有類似的相鄰對象,以標記它們以進行刪除。我試圖修改維基百科上的僞代碼,但都陷入了僵局。實施洪水填充算法的變體。

列表中的每個對象都有一個int X值,一個int Y值,一個Name和一個bool以標記爲刪除。我想匹配這個名字。

該程序掛起沒有try-catch,只是退出。它不會返回錯誤消息。這是我迄今爲止,試圖找到任何直接上面的對象。

//Find neighbouring bubbles 
    gameGrid.DetectNeighbours2(gameGrid.planets.Last(), gameGrid.planets.Last().name); 


    //Flood fill algorithm to detect all connected planets 
     internal void DetectNeighbours(Planet p, Planet.Name planetName) 
     { 
      try 
      { 
       if (p.planet != planetName) 
        return; 

       p.deletable = true; 

       DetectNeighbours(GetTopNode(p), planetName); 
      } 

      catch (Exception err) 
      { 
       Debug.WriteLine(err.Message); 
      } 
     } 


     internal Planet GetTopNode(Planet b) 
     { 
      foreach (Planet gridPlanet in planets) 
      { 
       if (gridPlanet .Y == b.Y - 50) 
        return gridPlanet ;  
      } 

      return b; //Don't think this is right, but couldn't think of alternative 
     } 

回答

1

或者你可以像這樣重寫它。

gameGrid.DetectNeighbours2(gameGrid.planets.Last()); 


//Flood fill algorithm to detect all connected planets 
    internal void DetectNeighbours(Planet p) 
    { 
     try 
     { 
      if (p == null || p.deletable) 
       return; 

      p.deletable = true; 

      DetectNeighbours(GetTopNode(p)); 
     } 

     catch (Exception err) 
     { 
      Debug.WriteLine(err.Message); 
     } 
    } 


    internal Planet GetTopNode(Planet b) 
    { 
     foreach (Planet gridPlanet in planets) 
     { 
      if (gridPlanet .Y == b.Y - 50) 
       return gridPlanet ;  
     } 

     return null; 
    } 
+0

我說對了,'p.planet!= planetName'這個比較純粹是爲了檢測沒有行星的情況嗎?那麼這個答案是正確的做法之一。 – unkulunkulu

+0

我是對的,那是在第一次之後添加的那個東西。 – unkulunkulu

+0

謝謝。這樣做更有意義,而且看起來更乾淨。 – David

1

首先,你應該修改這個字符串,這樣的:

if (p.planet != planetName || p.deletable) 
    return; 

,所以你不要再和再次訪問同一個星球上。

它應該至少減輕掛起(實際上無限遞歸)。

但無論如何,這個算法不應該工作,因爲你只能減少y值,但你想嘗試在所有方向上移動。

+0

謝謝,該行確實解決了無限遞歸問題。 我試圖讓它在添加其他方面之前首先在一個方向上工作。我期待以上任何東西仍然被刪除。 – David

+0

這是主要的問題,我想我現在能夠到達終點線。再次感謝,感謝。 – David