Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 2

Here's an implementation of the fastest flood fill algorithm with ArrayList for

Bitmap in Java for Android:

```java
public void floodFill(Bitmap bitmap, int x, int y, int targetColor, int
replacementColor) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
int[] pixels = new int[width * height];
bitmap.getPixels(pixels, 0, width, 0, 0, width, height);

int index = y * width + x;


int currentColor = pixels[index];
if (currentColor == targetColor) {
return;
}

ArrayList<Integer> queue = new ArrayList<>();


queue.add(index);

while (!queue.isEmpty()) {
int current = queue.remove(queue.size() - 1);
if (pixels[current] == currentColor) {
pixels[current] = replacementColor;

int xCurrent = current % width;


int yCurrent = current / width;

if (xCurrent > 0) {
queue.add(current - 1);
}
if (xCurrent < width - 1) {
queue.add(current + 1);
}
if (yCurrent > 0) {
queue.add(current - width);
}
if (yCurrent < height - 1) {
queue.add(current + width);
}
}
}

bitmap.setPixels(pixels, 0, width, 0, 0, width, height);


}
```

This implementation uses an ArrayList instead of a Queue for storing the pixels
that need to be filled. An ArrayList can provide faster access to the last element
compared to a LinkedList.

The algorithm starts by checking the color of the pixel at the starting point (x,
y). If the color is the same as the target color, it returns without doing
anything. Otherwise, it adds the starting pixel to the ArrayList and begins the
flood fill process.

The while loop continues until the ArrayList is empty. For each pixel in the
ArrayList, it checks if the color is the same as the current color. If it is, it
changes the color of the pixel to the replacement color and adds its neighboring
pixels to the ArrayList (if they haven't already been added).

Finally, the modified pixel array is set back to the bitmap using the setPixels
method.

Written by Chatsonic

You might also like