'Count number of polygons within a polyline

I have a collection of vertices that have been drawn sequentially by a user and I need to count how many enclosed areas there are within this shape. I have managed to find the intersecting points of crossing segments so I was thinking of walking along the path the initial shape was drawn since I have the direction each edge was drawn but, I'm unsure how to create a collection of polygons found within the shape.

Any help would be greatly appreciated!

Example of a shape I'm dealing with: enter image description here



Solution 1:[1]

Assuming you have list of edges for every vertex:

Choose the lowermost vertex (below 4 at your picture).

Follow the edge with smallest angle from OX.

If vertex has more than one outgoing edges, put it into a queue and follow the last edge in CCW order.

In this case you go around region 4 until initial point is met, putting three vertices in the queue. Then extract vertex (here rightmost) and walk around region 5, next region 3, then 2 and 1.

Solution 2:[2]

If you are using NetTopologySuite you can use NetTopologySuite.Operation.Polygonize.Polygonizer. You have to make sure that your input LineStrings are correctly noded.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 MBo
Solution 2 FObermaier