Android的洪水填充算法洪水、算法、Android

2023-09-12 02:01:19 作者:笑脸赢人脉

有谁知道一个迭代,高效的算法洪水填充?

Does anyone know a iterative and efficient algorithm for flood-fill?

或者有什么办法来实现递归此时,floodFill 算法没有堆栈溢出错误?

Or is there any way to implement recursive floodfill algorithm without stack overflow error?

试过一个@ 洪水填充使用堆栈 但我不能找到一种方法来工作,黑白图像。

Tried the one @ Flood fill using a stack but i cant find a way to work on white and black image.

推荐答案

这个算法为我工作不错。

this algorithm worked good for me.

private void FloodFill(Bitmap bmp, Point pt, int targetColor, int replacementColor) 
{
    Queue<Point> q = new LinkedList<Point>();
    q.add(pt);
    while (q.size() > 0) {
        Point n = q.poll();
        if (bmp.getPixel(n.x, n.y) != targetColor)
            continue;

        Point w = n, e = new Point(n.x + 1, n.y);
        while ((w.x > 0) && (bmp.getPixel(w.x, w.y) == targetColor)) {
            bmp.setPixel(w.x, w.y, replacementColor);
            if ((w.y > 0) && (bmp.getPixel(w.x, w.y - 1) == targetColor))
                q.add(new Point(w.x, w.y - 1));
            if ((w.y < bmp.getHeight() - 1)
                    && (bmp.getPixel(w.x, w.y + 1) == targetColor))
                q.add(new Point(w.x, w.y + 1));
            w.x--;
        }
        while ((e.x < bmp.getWidth() - 1)
                && (bmp.getPixel(e.x, e.y) == targetColor)) {
            bmp.setPixel(e.x, e.y, replacementColor);

            if ((e.y > 0) && (bmp.getPixel(e.x, e.y - 1) == targetColor))
                q.add(new Point(e.x, e.y - 1));
            if ((e.y < bmp.getHeight() - 1)
                    && (bmp.getPixel(e.x, e.y + 1) == targetColor))
                q.add(new Point(e.x, e.y + 1));
            e.x++;
        }
    }
}