Set up top row and left column
int maxi = grid [ N - 1 ] [ N - 1 ] ; for ( int i = N - 2 ; i >= 0 ; i -- ) { grid [ N - 1 ] [ i ] = min ( grid [ N - 1 ] [ i ] , grid [ N - 1 ] [ i + 1 ] + 1 ) ; maxi = max ( grid [ N - 1 ] [ i ] , maxi ) ; } for ( int i = N - 2 ; i >= 0 ; i -- ) { grid [ i ] [ N - 1 ] = min ( grid [ i ] [ N - 1 ] , grid [ i + 1 ] [ N - 1 ] + 1 ) ; maxi = max ( grid [ i ] [ N - 1 ] , maxi ) ; }