【问题标题】:Flood fill algorithm analysis洪水填充算法分析
【发布时间】:2012-08-16 15:26:20
【问题描述】:

我有一些洪水填充算法的方法。很简单

  1. 前往顶部的第一个障碍物。

  2. 将像素颜色更改为底部

  3. 更改时检查左/右像素是否为不同颜色

  4. 如果是:也为该列着色(stack.push())

  5. 循环。

        Stack<Point> st = new Stack<Point>();
        bool spLeft, spRight;
    
        Bitmap b = canvas.buffer;
    
        st.Push(start);
        spLeft = spRight = false;
    
    
        Point p = new Point();
        while (st.Count > 0) 
        {
            //going as far top as possible (finding first obstacle)
            p = st.Pop();
            while (p.Y >= 0 && b.GetPixel(p.X, p.Y) == oldColor) p.Y--;
            p.Y++;
            spLeft = spRight = false;
    
    
            //looping on every oldColored pixel in column
            while (p.Y < b.Height && b.GetPixel(p.X, p.Y) == oldColor) {
                b.SetPixel(p.X, p.Y, state.currentColor); //setting new color
    
                //checking if left pixel is oldColored and if it doesn't belong to span
                if (!spLeft && p.X > 0 && b.GetPixel(p.X - 1, p.Y) == oldColor) {
                    st.Push(new Point(p.X - 1, p.Y));
                    spLeft = true;
                }
                //checking if left pixel isn't oldColored and if it belongs to span
                else if (spLeft && p.X > 0 && b.GetPixel(p.X - 1, p.Y) != oldColor) {
                    spLeft = false;
                }
                if (!spRight && p.X < b.Width - 1 && b.GetPixel(p.X + 1, p.Y) == oldColor) {
                    st.Push(new Point(p.X + 1, p.Y));
                    spRight = true;
                }
                else if (spRight && p.X < b.Width - 1 && b.GetPixel(p.X + 1, p.Y) != oldColor) {
                    spRight = false;
                }
                p.Y++;
            }
    
        }
    

关键是我只是不明白这些部分

    //checking if left pixel isn't oldColored and if it belongs to span
    else if (spLeft && p.X > 0 && b.GetPixel(p.X - 1, p.Y) != oldColor) {
    spLeft = false;

    else if (spRight && p.X < b.Width - 1 && b.GetPixel(p.X + 1, p.Y) != oldColor) {
    spRight = false;
            }

没有这些,代码可以正常工作,而且似乎有相同数量的迭代。你能帮我弄清楚这些线是真的没用还是我只是不理解它们? (我不敢相信我的朋友会毫无目的地放它们)

【问题讨论】:

  • 为什么不问问你的朋友为什么添加它们?

标签: c# algorithm fill


【解决方案1】:

它们允许填充多个区域。开头的 if 语句检查它们是否为假并将一个像素添加到堆栈中。当该区域完成时,它们会重置。

如果不重置 spLeft,区域 2 将不会被填充,因为当遇到第一个区域时,它会被设置为 true(这样可以避免不必要地向堆栈添加批次)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-16
    • 1970-01-01
    • 2019-08-22
    • 2011-07-10
    • 1970-01-01
    相关资源
    最近更新 更多