Sometimes we'd like a area fill algorithm that replaces all
connected pixels of a selected color with a fill color.
The flood-fill algorithm does exactly that.
public void floodFill(int x, int y, int fill, int old) {
if ((x < 0) || (x >= raster.width)) return;
if ((y < 0) || (y >= raster.height)) return;
if (raster.getPixel(x, y) == old) {
raster.setPixel(fill, x, y);
floodFill(x+1, y, fill, old);
floodFill(x, y+1, fill, old);
floodFill(x-1, y, fill, old);
floodFill(x, y-1, fill, old);
}
}
This algorithm replaces old pixels with the fill color.
Usually, the initial pixel (x, y) establishes the old value.