我编写了一个方法来填充由 m x n 矩阵表示的位图。我想做的是将初始像素插入堆栈,然后在 while 循环中从堆栈中弹出一个元素,为其着色并推送相邻像素(如果它们与初始像素的初始颜色相同)。
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());
}
}
但由于我似乎无法发现的原因,它不起作用。输出(调试行未注释)如下:
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
...就这样无限循环下去。可能是什么问题?
最佳答案
你的打印语句说的是一回事,你的代码做的是另一回事! ;)
例如:
fillStack.push(new Point(x, y - 1));
System.out.println("Pushing " + currentPoint.x + " " + (currentPoint.y - 1));
看看你是否能发现差异...
关于java - 堆栈不断弹出相同的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9515129/