Find triangles in a graph

Posted By: PadMalcom

Find triangles in a graph - 01/15/17 20:45

Hi, here is a little brain teaser:

I have a graph consisting of lines and looking exactly like a mesh - so the lines are arranged as if they were connected as triangles. Now I want to find all triangles in that graph and create vertices and indices out of them.

How can I do it?
Posted By: Superku

Re: Find triangles in a graph - 01/16/17 16:29

I don't know what's the data structure for the graph like but I guess you should be able to iterate over all nodes and their direct neighbors easily, right? If so, then I think the following should work:

1) Iterate over all nodes.
2) For each node A, iterate over its neighbors B_0,1,2,..
3) For each neighbor B_i, iterate over its neighbors C_0,1,2,...
4) If C_j != A and C_j != B_i and there exists k with C_j == B_k, then there's a cycle of length 3 (or is that 2? not sure about definitions).
5) Either add 3 entries with the nodes' indices to a list or one entry with 3 values. Count the number of triangles.
6) Allocate mesh with #nodes and #triangles and setup the index buffer with the entries from the list.
© 2024 lite-C Forums