Implement a flood fill.

A flood fill is a way of filling an area using color banks to define the contained area or a target color which "determines" the area (the valley that can be flooded; Wikipedia uses the term target color). It works almost like a water flooding from a point towards the banks (or: inside the valley): if there's a hole in the banks, the flood is not contained and all the image (or all the "connected valleys") get filled.

To accomplish the task, you need to implement just one of the possible algorithms (examples are on Wikipedia). Variations on the theme are allowed (e.g. adding a tolerance parameter or argument for color-matching of the banks or target color).

 
Testing: the basic algorithm is not suitable for truecolor images; a possible test image is the one shown on the right box; you can try to fill the white area, or the black inner circle.

include c:\cxpl\codes;
 
proc    Flood(X, Y, C, C0);     \Fill an area of color C0 with color C
int     X, Y,   \seed coordinate (where to start)
        C, C0;  \color to fill with and color to replace
def     S=8000; \size of queue (must be an even number)
int     Q(S),   \queue (FIFO)
        F, E;   \fill and empty indexes
 
        proc    EnQ(X, Y);      \Enqueue coordinate
        int     X, Y;
        [Q(F):= X;
        F:= F+1;
        Q(F):= Y;
        F:= F+1;
        if F >= S then F:= 0;
        ];      \EnQ
 
        proc    DeQ;            \Dequeue coordinate
        [X:= Q(E);
        E:= E+1;
        Y:= Q(E);
        E:= E+1;
        if E >= S then E:= 0;
        ];      \DeQ
 
[F:= 0;  E:= 0;
EnQ(X, Y);
while E # F do
        [DeQ;
        if ReadPix(X, Y) = C0 then
                [Point(X, Y, C);
                EnQ(X+1, Y);    \enqueue adjacent pixels
                EnQ(X-1, Y);
                EnQ(X, Y+1);
                EnQ(X, Y-1);
                ];
        ];
];      \Flood
 
def     Size = 30.0;
int     X, Y;
real    Ang, Dist;
[SetVid($101);                  \set 640x480 graphics with 256 colors
 
Ang:= 0.0;                      \draw some flower petals
repeat  Dist:= Size*(Cos(Ang*3.0) - 1.0);
        X:= fix(Dist*Cos(Ang));
        Y:= fix(Dist*Sin(Ang));
        Point(X+320, 240-Y, $F);
        Ang:= Ang + 0.001;      \draw dots close together to prevent leaks
until   Ang >= 2.0*3.14159;
 
Flood(330, 240, $2A, 0);        \color the petals
Flood(310, 230, $2C, 0);
Flood(310, 250, $2E, 0);
 
if ChIn(1) then [];             \wait for keystroke
SetVid(3);                      \restore normal text mode
]