0
我寫了一個方法,填充由m×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
...並且它在這樣一個無限循環中繼續。可能是什麼問題?
哦,我,我不敢相信,我一直在尋找這個東西了一個小時,couldn看不到這個。謝謝:D – hattenn 2012-03-01 11:23:42
@hatten - 哈哈,有時你需要的是另一雙眼睛...... – Nim 2012-03-01 11:24:38