# Determine whether a polygon is completely surrounded using QGIS [closed]

I have a shapefile dataset of polygons. I would like to find those polygons that are completely surrounded/enclosed. Mathematically, this means that the perimeter of Polygon A should equal the sum of the line segments of its neighboring polygons B,C,D,E,...n+1. If they are NOT completely enclosed, then the perimeter of Polygon A /= the sum of intersecting line segments of neighboring polygons B,C,D,E...n+1.

The polygons are irregularly shaped and not always square, so there aren't always the same # of polygon neighbors.

I found this post discussing how to do this in SQL, but I'd like to know how to write something similar in PyQGIS 3. (Determine if a polygon is not enclosed by other polygons).

I'm new at Python programming, but I imagine I basically need to:

• import pyQGIS libraries
• iface select active layer
• calculate new perimeter field (data is in planar proj)
• loop for every polygon in active layer: *select polygons that intersect *sum intersecting line lengths *create new field of summed intersection lengths *select where the two fields are equal

Is there a way to do this in QGIS? Would I need to convert to lines first?

Example of what I want to select for based on this approach:

To build up on this solution (finding landlocked countries), you could also choose a completely different approach, without using Python.

Dissolve all your polygons, creating a new layer named `dissolved`. Apply a small negative buffer to this layer so that the polygon features at the margin project beyond it. Than check which of your original polygons are (completely) within this buffer. You can do this with this expression on the original polygon layer:

``````within(
\$geometry,
buffer (
geometry (
get_feature_by_id(
'dissolved',
1
)
),
-1
)
)
``````

Screenshot - the expression used with `Select by expression` - dissolved polygon in red outline, polygon selected by the expression in yellow: