Strategy game dynamic borders ;-;

Marching squares are grid based, so you can exploit that. Preserve the grid information for each segment (keep them in a 2d array or a hashmap) and then you can use a flood-fill like search to iteratively find adjacencies starting from any segment. Each resulting polyline will be either a closed loop or an open strip.