Past two : bottom right to top left
for ( int i = N - 2 ; i >= 0 ; i -- ) { for ( int j = N - 2 ; j >= 0 ; j -- ) { grid [ i ] [ j ] = min ( grid [ i ] [ j ] , min ( grid [ i + 1 ] [ j ] + 1 , grid [ i ] [ j + 1 ] + 1 ) ) ; maxi = max ( grid [ i ] [ j ] , maxi ) ; } } return ! maxi ? -1 : maxi ; }