Flood fill recursive algorithm

后端 未结 3 1264
一向
一向 2021-01-05 08:14

I\'m trying to make an algorithm that could fill an int array in c#. Basically, as the fill tool in MS Paint, I have a color and if I choose (x,y) coordinates in the array,

3条回答
  •  别那么骄傲
    2021-01-05 08:32

    How about using a stack/queue to manage the remaining work?

    public void Fill(int[,] array, int x, int y, int newInt)
    {
        int initial = array[x,y];
    
        Queue> queue = new Queue>();
        queue.Push(new Tuple(x, y));
    
        while (queue.Any())
        {
            Tuple point = queue.Dequeue();
    
            if (array[point.Value1, point.Value2] != initial)
                continue;
    
            array[point.Value1, point.Value2] = newInt;
    
            EnqueueIfMatches(array, queue, point.Value1 - 1, point.Value2, initial);
            EnqueueIfMatches(array, queue, point.Value1 + 1, point.Value2, initial);
            EnqueueIfMatches(array, queue, point.Value1, point.Value2 - 1, initial);
            EnqueueIfMatches(array, queue, point.Value1, point.Value2 + 1, initial);        
        }
    }
    
    private void EnqueueIfMatches(int[,] array, Queue> queue, int x, int y, int initial)
    {
        if (x < 0 || x >= array.GetLength(0) || y < 0 || y >= array.GetLength(1))
            return;
    
        if (array[x, y] == initial)
           queue.Enqueue(new Tuple(x, y));
    }
    

提交回复
热议问题