【问题标题】:Implementing a variation of the Flood Fill algorithm.实现洪水填充算法的变体。
【发布时间】:2011-07-28 22:05:03
【问题描述】:

我正在尝试使用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
        }

【问题讨论】:

    标签: c# algorithm xna


    【解决方案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;
        }
    

    【讨论】:

    • 我是否正确添加了比较 p.planet != planetName 纯粹是为了检测上面没有行星的情况?那么这个答案是正确的方法之一。
    • 我是对的,在第一个之后添加的那个是偶然的。
    • 谢谢。这样做更有意义,而且看起来也更干净。
    • @David,没错。此外,即使两个行星同名,它也能正常工作。
    【解决方案2】:

    首先,您应该将此字符串修改为:

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

    这样您就不会一次又一次地访问同一个星球。

    它至少应该减轻挂起(实际上是无限递归)。

    但无论如何,这个算法不应该工作,因为你只减少了y 的值,但你想尝试向所有方向移动。

    【讨论】:

    • 谢谢,那行确实解决了无限递归问题。在添加其他方向之前,我试图让它首先朝一个方向工作。我期待上面的任何内容仍然会被删除。
    • 这是主要问题,我想我现在可以自己到达终点了。再次感谢,不胜感激。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-11
    • 2014-02-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多