【问题标题】:Partially recursive flood-fill function部分递归的洪水填充函数
【发布时间】:2016-03-04 22:05:05
【问题描述】:

这是一个任务。我们被要求制作完全递归和部分递归的洪水填充函数。我能够简单地完成完全递归函数,但我在部分递归函数上苦苦挣扎。我可以对此提出第二意见,因为我已经说服自己我做对了,并且不知道该去哪里寻找错误了。我在每一行代码的逻辑中都包含了 cmets。

 //setup function for the partially recursive function.
void DoFloodFill( int x, int y )
{
    x -= m_nTestShapeX;
    y -= m_nTestShapeY;
    m_nStartColor = GetPixel(x,y) | 0xff000000;
    Graphics canvas = getGraphics();
    canvas.setColor( m_objSelectedColor );

    int w = m_objShape.getWidth();
    int h = m_objShape.getHeight();


    if( m_nStartColor == m_nSelectedColor)
    {
        return;
    }

    FloodFill( x, y, w, h, canvas);
}

void FloodFill( int x, int y, int w, int h, Graphics canvas )
{
    int xx = 0, right = 0;

    // if the x or y values are out of bounds return
    if(x >= w || y >= h || x < 0 || y < 0)
        return; 

    //if the passed in pixel is not the start color return
    //base case for recursion
    if(GetPixel(x,y) != this.m_nStartColor)
        return;

    //used to walk right untill a wall or bound is hit.
    xx = x;

    //walk right from the current pixel setting it to the desired color
    while(xx < w && this.m_nStartColor == GetPixel(xx,y))
    {
        this.SetPixel(xx+100, y+100, canvas);
        this.SetPixel(xx+100, y+100, this.m_nSelectedColor);
        xx++;
    }
    //save the x value of the the pixel where the wall is
    right = xx;

    //used to left starting one pixel to the left of the current pixel 
    xx = x-1;

    //walk left of the current pixel setting it to the desired color
    while(xx >= 0 && this.m_nStartColor == GetPixel(xx,y) )
    {
        this.SetPixel(xx+100, y+100, canvas);
        this.SetPixel(xx+100, y+100, this.m_nSelectedColor);
        xx--;
    }

    //start from where the left wall is 
    for(; xx < right; xx++)
    {
        //now this should go up one/down one and repeat the right and left walks
        //the base cases should prevent this from running in most cases
        //because when it tries to walk down and the start color is not == to the current pixel it will return.
        FloodFill(xx,y+1,w,h,canvas);
        FloodFill(xx,y-1,w,h,canvas);
    }
}

这是我点击一个像素时的样子。我点击的地方标记为红色。 eventual stack-overflows

【问题讨论】:

  • + 100?可能是我。
  • @JoopEggen 他不能因为名声?
  • 抱歉,+100 是像素实际保存位置与它应该显示在屏幕上的位置的偏移量,如果那样的话。
  • 更新了 while 循环 this.SetPixel(xx+100, y+100, canvas); this.SetPixel(xx, y, this.m_nSelectedColor);在某些时候仍然会出现堆栈溢出
  • 解决了,谢谢! @JoopEggen

标签: java recursion flood-fill


【解决方案1】:

从上面的代码改动:

this.SetPixel(xx+100, y+100, m_nSelectedColor);

this.SetPixel(xx, y, m_nSelectedColor);

【讨论】:

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