I’ve written a method that fills a bitmap represented by a m x n matrix. What I’m trying to do is to push the initial pixel to a stack, then in a while loop pop an element from the stack, color it and push neighboring pixels if they are the same color as the initial color of the initial pixel.
public void fill(int x, int y, char c) {
char tempColor = this.bitmap[y - 1][x - 1];
Point currentPoint;
Stack<Point> fillStack = new Stack<Point>();
fillStack.push(new Point(x, y));
do {
currentPoint = fillStack.pop();
// System.out.println(currentPoint.x + " " + currentPoint.y);
// System.out.println("Current state of the stack:");
// for (Point p: fillStack)
// System.out.println(p.x + " " + p.y);
this.bitmap[currentPoint.y - 1][currentPoint.x - 1] = c;
if (currentPoint.y - 1 > 0 && this.bitmap[currentPoint.y - 2][currentPoint.x - 1] == tempColor) {
fillStack.push(new Point(x, y - 1));
// System.out.println("Pushing " + currentPoint.x + " " + (currentPoint.y - 1));
}
if (currentPoint.y - 1 < n - 1 && this.bitmap[currentPoint.y][currentPoint.x - 1] == tempColor) {
fillStack.push(new Point(x, y + 1));
// System.out.println("Pushing " + currentPoint.x + " " + (currentPoint.y + 1));
}
if (currentPoint.x - 1 > 0 && this.bitmap[currentPoint.y - 1][currentPoint.x - 2] == tempColor) {
fillStack.push(new Point(x - 1, y));
// System.out.println("Pushing " + (currentPoint.x - 1) + " " + currentPoint.y);
}
if (currentPoint.x - 1 < m - 1 && this.bitmap[currentPoint.y - 1][currentPoint.x] == tempColor) {
fillStack.push(new Point(x + 1, y));
// System.out.println("Pushing " + (currentPoint.x + 1) + " " + currentPoint.y);
}
} while (!fillStack.isEmpty());
}
}
But it doesn’t work for a reason I can’t seem to spot. The output (debugging lines uncommented) is as follows:
3 3 Current state of the stack: Pushing 3 2 Pushing 3 4 Pushing 4 3 4 3 Current state of the stack: 3 2 3 4 Pushing 4 2 Pushing 4 4 Pushing 5 3 4 3 Current state of the stack: 3 2 3 4 3 2 3 4 Pushing 4 2 Pushing 4 4 Pushing 5 3 4 3 Current state of the stack: 3 2 3 4 3 2 3 4 3 2 3 4 Pushing 4 2 Pushing 4 4 Pushing 5 3 4 3 Current state of the stack: 3 2 3 4 3 2 3 4 3 2 3 4 3 2 3 4 Pushing 4 2 Pushing 4 4 Pushing 5 3 4 3 Current state of the stack: 3 2 3 4 3 2 3 4 3 2 3 4 3 2 3 4 3 2 3 4 Pushing 4 2 Pushing 4 4 Pushing 5 3 4 3 Current state of the stack: 3 2 3 4 3 2 3 4 3 2 3 4 3 2 3 4 3 2 3 4 3 2 3 4 Pushing 4 2 Pushing 4 4 Pushing 5 3 4 3 Current state of the stack: 3 2 3 4 3 2 3 4 3 2 3 4 3 2 3 4 3 2 3 4 3 2 3 4 3 2 3 4 Pushing 4 2 Pushing 4 4 Pushing 5 3 4 3 Current state of the stack: 3 2 3 4 3 2 3 4 3 2 3 4 3 2 3 4 3 2 3 4 3 2 3 4 3 2 3 4 3 2 3 4 Pushing 4 2 Pushing 4 4 Pushing 5 3 4 3 Current state of the stack: 3 2 3 4 3 2 3 4 3 2 3 4 3 2 3 4 3 2 3 4 3 2 3 4 3 2 3 4 3 2 3 4 3 2 3 4
… and it goes on like this in an endless loop. What can be the problem?
Your print statements say one thing, your code does another! 😉
for example:
See if you can spot the difference…