Pass one : top left to bottom right
for ( int i = 1 ; i < N ; i ++ ) { for ( int j = 1 ; j < N ; j ++ ) { grid [ i ] [ j ] = grid [ i ] [ j ] == 1 ? 0 : min ( grid [ i - 1 ] [ j ] , grid [ i ] [ j - 1 ] ) + 1 ; } }