Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to repaint all image pixels recursively

Tags:

c++

recursion

I'm trying to repaint all the image pixels recursively but it fails because the stack overflows. But why?

void go( short x, short y ) {

    if ( x < 0 || y < 0 || x >= _w || y >= _h ) return ;

    _image[ x ][ y ] = someColor;

    go( x + 1, y );
    go( x - 1, y );
    go( x, y - 1 );
    go( x, y + 1 ); 

}
like image 418
JavaRunner Avatar asked Nov 23 '25 08:11

JavaRunner


2 Answers

This function call will never stop.

void go( short x, short y ) {    

    if ( x < 0 || y < 0 || x >= _w || y >= _h ) return ;

    _image[ x ][ y ] = someColor;

    go( x + 1, y );
    go( x - 1, y ); 
    go( x, y - 1 );
    go( x, y + 1 ); 

}

If you call your function with x=0,y=0 (go( 0, 0 );) it will do this

    _image[ 0 ][ 0 ] = someColor;    
    go( 1, 0 );
    go( -1, 0 ); 
    go( 0, -1 );
    go( 0, 1 ); 

OK now let's check the function call to go( 1, 0 );:

    _image[ 1 ][ 0 ] = someColor;    
    go( 2, 0 );
    go( 0, 0 );  //ohoh
    go( 1, -1 );
    go( 1, 1 ); 

So you can see that go( 0, 0 ) calls go( 1, 0 ) callsgo( 0, 0 ) calls go( 1, 0 ) callsgo( 0, 0 ) calls go( 1, 0 ) callsgo( 0, 0 ) calls go( 1, 0 ) callsgo( 0, 0 ) calls go( 1, 0 ) calls ....

That's why you have a stack overflow. You won't ever get out.


Why don't you just create 2 loops and iterate over these? As your example always iterates x from 0 to _w and yfrom 0 to _hI would just get rid of these parameters at all.

You can just use this:

void go( short x, short y ) {    
    for(short x = 0; x < _w; x++) {
        for(short y = 0; y < _h; y++) {
            _image[ x ][ y ] = someColor;
        }
    }
}
like image 68
Simon Kraemer Avatar answered Nov 24 '25 20:11

Simon Kraemer


I think you're missing one base case of initial value of _image array, as to stop re-filling same values over and over

if ( _image[x][y] != previousColor ) 
        return;
like image 33
P0W Avatar answered Nov 24 '25 20:11

P0W