I have the edge list of an undirected graph which consists of disjoint "cycles" only. Example:
{{1, 2}, {2, 3}, {3, 4}, {4, 1}, {5, 6}, {6, 7}, {7, 5}}
Each vertex has exactly two edges connecting to it. Each cycle has at least three vertices. The vertices are denoted by integers $1..n$. The edge list is given in some random order. The edges appear in random orientations (i.e. {1,2}
might be given as {2,1}
)
I need to break the graph into cycles and sort the vertices in the order they're connected. For example, if the input is:
{{7, 6}, {5, 6}, {4, 3}, {3, 2}, {4, 1}, {2, 1}, {7, 5}}
then I want the output
{ {1, 2, 3, 4},
{5, 6, 7} }
The first sublist corresponds to the tetragon, the second one corresponds to the triangle. The vertices must appear in the order they're connected.
Performance requirements: the maximum vertex count is a few thousand---it should run near-instantaneously for an input of this size. An $n \log n$ solution is possible. However, I'm more interested in a concise and elegant solution than a performant one using e.g. Compile
.
Note: while it was easiest to state the problem in terms of graphs, it's not really a graph theoretical problem, so don't feel compelled to use Graph
unless it's really advantageous.
Clarification: This question is not (only) about finding connected components. It is about ordering vertices along the cycles. Actually my practical problem is that I have the edges of a polygon in random order and orientation, and I need to sort them so I can use them in Polygon
and related primitives.
A sample dataset can be downloaded using Import["http://w504215.open.ge.tt/1/files/3XgvcEF/0/blob?download", "WDX"]
.
Import
link is unfortunately now broken. Since this has a good answer it could be removed? BTW thanks for this :). $\endgroup$