部分递归填充功能

时间:2016-03-04 22:05:06

标签: java recursion flood-fill

这是作业。我们被要求进行完全递归和部分递归的泛洪填充功能。我能够完全完成递归函数,但我在部分递归函数上挣扎。我可以对此使用第二种意见,因为我已经说服自己我已经做得对,并且不知道在哪里寻找错误。我在每行代码中都包含了对逻辑的注释。

 //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

1 个答案:

答案 0 :(得分:0)

从上面的代码更改:

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

this.SetPixel(xx, y, m_nSelectedColor);