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 ] = Math . Min ( grid [ N - 1 , i ] , grid [ N - 1 , i + 1 ] + 1 ) ; maxi = Math . Max ( grid [ N - 1 , i ] , maxi ) ; } for ( int i = N - 2 ; i >= 0 ; i -- ) { grid [ i , N - 1 ] = Math . Min ( grid [ i , N - 1 ] , grid [ i + 1 , N - 1 ] + 1 ) ; maxi = Math . Max ( grid [ i , N - 1 ] , maxi ) ; }