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.

 
 
program FloodFillTest;
 
{$APPTYPE CONSOLE}
{$R *.res}
 
uses
  Winapi.Windows,
  System.SysUtils,
  System.Generics.Collections,
  vcl.Graphics;
 
procedure FloodFill(bmp: tBitmap; pt: TPoint; targetColor: TColor;
  replacementColor: TColor);
var
  q: TQueue<TPoint>;
  n, w, e: TPoint;
begin
  q := TQueue<TPoint>.Create;
 
  q.Enqueue(pt);
 
  while (q.Count > 0) do
  begin
    n := q.Dequeue;
    if bmp.Canvas.Pixels[n.X, n.Y] <> targetColor then
      Continue;
 
    w := n;
    e := TPoint.Create(n.X + 1, n.Y);
 
    while ((w.X >= 0) and (bmp.Canvas.Pixels[w.X, w.Y] = targetColor)) do
    begin
      bmp.Canvas.Pixels[w.X, w.Y] := replacementColor;
      if ((w.Y > 0) and (bmp.Canvas.Pixels[w.X, w.Y - 1] = targetColor)) then
        q.Enqueue(TPoint.Create(w.X, w.Y - 1));
      if ((w.Y < bmp.Height - 1) and (bmp.Canvas.Pixels[w.X, w.Y + 1] = targetColor)) then
        q.Enqueue(TPoint.Create(w.X, w.Y + 1));
      dec(w.X);
    end;
 
    while ((e.X <= bmp.Width - 1) and (bmp.Canvas.Pixels[e.X, e.Y] = targetColor)) do
    begin
      bmp.Canvas.Pixels[e.X, e.Y] := replacementColor;
      if ((e.Y > 0) and (bmp.Canvas.Pixels[e.X, e.Y - 1] = targetColor)) then
        q.Enqueue(TPoint.Create(e.X, e.Y - 1));
 
      if ((e.Y < bmp.Height - 1) and (bmp.Canvas.Pixels[e.X, e.Y + 1] = targetColor)) then
        q.Enqueue(TPoint.Create(e.X, e.Y + 1));
      inc(e.X);
    end;
  end;
  q.Free;
end;
 
var
  bmp: TBitmap;
 
begin
  bmp := TBitmap.Create;
  try
    bmp.LoadFromFile('Unfilledcirc.bmp');
    FloodFill(bmp, TPoint.Create(200, 200), clWhite, clRed);
    FloodFill(bmp, TPoint.Create(100, 100), clBlack, clBlue);
    bmp.SaveToFile('Filledcirc.bmp');
  finally
    bmp.Free;
  end;
 
end.
 