Set up top row and left column
for ( int i = 1 ; i < N ; i ++ ) grid [ 0 ] [ i ] = grid [ 0 ] [ i ] == 1 ? 0 : grid [ 0 ] [ i - 1 ] + 1 ; for ( int i = 1 ; i < N ; i ++ ) grid [ i ] [ 0 ] = grid [ i ] [ 0 ] == 1 ? 0 : grid [ i - 1 ] [ 0 ] + 1 ;