Check if the cell is within the boundaries or contains a 1
if ( x < 0 or x >= M or y < 0 or y >= N or grid [ x ] [ y ] ) : NEW_LINE INDENT continue NEW_LINE DEDENT q . append ( [ x , y ] ) NEW_LINE grid [ x ] [ y ] = 1 NEW_LINE cnt -= 1 NEW_LINE ans += 2 NEW_LINE return ans NEW_LINE