2011-07-28 33 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