views:

10

answers:

0

Hi,

I am trying to implement flood-fill on a 2d matrix. It is similar to the fill color of MS Paint or any other painting application. Following is the code

void FloodFill(int x, int y, Color targetColor, Color replacementColor)
    {
        LinkedList<Point> check = new LinkedList<Point>();

        if (targetColor != replacementColor)
        {
            check.AddLast(new Point(y, x));
            while (check.Count > 0)
            {
                Point cur = check.First.Value;
                check.RemoveFirst();

                foreach (Point off in new Point[] {
            new Point(0, -1), new Point(0, 1), 
            new Point(-1, 0), new Point(1, 0)})
                {
                    Point next = new Point(cur.X + off.X, cur.Y + off.Y);
                    if (next.X >= 0 && next.Y >= 0 &&
                        next.X < MaxColumn &&
                        next.Y < MaxRow)
                    {
                        Color tColor;
                        if (dMatrix[(int)next.X, (int)next.Y] == null)
                        {
                            tColor = Colors.White;
                        }
                        else
                        {
                            tColor = dMatrix[(int)next.X, (int)next.Y].CellColor;
                        }

                        if (tColor == targetColor)
                        {
                            check.AddLast(next);

                            Cell c = new Cell();
                            c.CellColor = replacementColor;
                            c.IsFilled = true;
                            dMatrix[(int)next.X, (int)next.Y] = c;
                        }
                    }
                }
            }
        }
    }

The above method works on a 2d matrix. The type of matrix is Cell (a custom class)

 class Cell
{
    Color cellColor=Colors.Black;
    bool isFilled = false;

    public bool IsFilled
    {
        get
        {
            return isFilled;
        }
        set
        {
            isFilled = value;
        }
    }
    public Color CellColor
    {
        get
        {
            return cellColor;
        }
        set
        {
            cellColor = value;
        }
    }
}

Following is the declaration of matrix

Cell[,] dMatrix=new Cell[50,50];

I have created this code from flood-fill algo. ( http://en.wikipedia.org/wiki/Flood_fill )

Now the problem is that for some position of the matrix it is working fine and for others it is either not working for filling other colors.