Check if the cell is within the boundaries or contains a 1
if ( x < 0 x >= M y < 0 y >= N grid [ x ] [ y ] > 0 ) continue ; q . add ( new pair ( x , y ) ) ; grid [ x ] [ y ] = 1 ; } } ++ ans ; } return ans ; }