Check all the 4 adjacent cells and marking them as visited if not visited yet also marking their height as 1 + height of cell ( x , y )
if ( x > 0 && vis [ x - 1 ] [ y ] == 0 ) { height [ x - 1 ] [ y ] = height [ x ] [ y ] + 1 ; vis [ x - 1 ] [ y ] = 1 ; q . push ( { x - 1 , y } ) ; } if ( y > 0 && vis [ x ] [ y - 1 ] == 0 ) { height [ x ] [ y - 1 ] = height [ x ] [ y ] + 1 ; vis [ x ] [ y - 1 ] = 1 ; q . push ( { x , y - 1 } ) ; } if ( x < M - 1 && vis [ x + 1 ] [ y ] == 0 ) { height [ x + 1 ] [ y ] = height [ x ] [ y ] + 1 ; vis [ x + 1 ] [ y ] = 1 ; q . push ( { x + 1 , y } ) ; } if ( y < N - 1 && vis [ x ] [ y + 1 ] == 0 ) { height [ x ] [ y + 1 ] = height [ x ] [ y ] + 1 ; vis [ x ] [ y + 1 ] = 1 ; q . push ( { x , y + 1 } ) ; } } }