We have answer of your question!

100% solved queries, no empty question

Question: Trying to repaint all image pixels recursively


0

Advertisement


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 ); 

}
Question author Javarunner | Source

Answer


1


Advertisement


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;
        }
    }
}
Answer author Simon-kraemer

Advertisement


Tickanswer.com is providing the only single recommended solution of the question Trying to repaint all image pixels recursively under the categories i.e c++ , recursion , . Our team of experts filter the best solution for you.

Related Search Queries:

You may also add your answer!