I want to implement the flood-fill algorithm for https://stackoverflow.com/questions/12995378/is-there-a-proper-algorithm-for-detecting-the-background-color-of-a-figure. I did it recursively, but I had a stack-overflow error. No matter - Wikipedia has a spot for a non-recursive, iterative solution.
It requires a queue. For school, we're not supposed to use Lists nor the Java Queue class (I don't even know if it does what I think it does, but it doesn't matter - I can't use it).
public class QueueOfPixeles
{
public Pixel[] elements;
public int numberOfElements;
public QueueOfPixeles()
{
numberOfElements = 0;
elements = new Pixel[1];
}
// Next pixel is supposed to return the last pixel element in the queue.
// When a pixel element is returned, it will become null in the system.
public Pixel nextPixel() {
Pixel result = null;
for (int i = elements.length - 1; i >= 0 && result == null; --i) {
result = elements[i];
if (result != null) {
elements[i] = null;
}
}
return result;
}
// Adds a new pixel to the queue.
// Then, it checks if the capacity of the vector has been reached.
public void add(Pixel pixel) {
elements[numberOfElements] = pixel;
++numberOfElements;
fixVector();
}
// If the vector capacity has been reached, create a new vector with all old elements
// but with more capacity.
private void fixVector() {
if (numberOfElements >= elements.length) {
Pixel[] newVector = new Pixel[(elements.length * 2) + 1];
for (int i = 0; i < numberOfElements; ++i) {
newVector[i] = elements[i];
}
elements = newVector;
}
}
}
WHAT IS IT SUPPOSED TO DO?
You should be able to add pixels to the end of the queue, and get the next pixel by using nextPixel()
. When you retrieve the next pixel, it should be removed from the queue automatically.
DOES IT WORK?
Yes, it seems to be working. I've done a few tests and it has indeed returned all I expected.
WHAT'S THE PROBLEM?
I'd like to get some feedback about this. I can only use vectors for this project, and I feel there is something rather not-efficient with the way I manage the pixels in the queue (converting the elements to null and just that etc, or asking for more capacity size instead of using the null-spaces I made).
What do you think?