Android 洪水填充算法 [英] Android flood-fill algorithm

查看:30
本文介绍了Android 洪水填充算法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

推荐答案

这个算法对我很有用.

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++;
        }
    }
}

这篇关于Android 洪水填充算法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆