How to implement flood fill to detect enclose space?

This is what’s happening.

also about this

I use a if statement to detect the name of the part it is touching to prevent this from happening.