开发者

Implementing a variation of the Flood Fill algorithm.

I'm trying to use the flood fill algorithm to find all of the similar adjacent objects in a list, to mark them for deletion. I've tried to adapt the pseudo code on Wikipedia, but have gotten stuck.

Each object in the list has an int X value, an int Y value,a Name and a bool to mark for deletion. I want to match on the name.

The program hangs without the try-catch, and just exits with it. It doesn't return an error message. Here's what I have so far, trying to find any objects directly above.

    //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
        }


Or you could rewrite it like this.

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;
    }


First, you should modify this string to this:

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

so you don't visit the same planet again and again.

It should at least alleviate the hangs (infinite recursion actually).

But anyway, this algorithm shouldn't work as you only decrease the y value, but you want to try to move in all the directions.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜