I am trying to find a better way to find all leaf nodes in my undirected waypoint graph.
This is how I define a leaf node:
A leaf node is a node that is never part of a cycle and so has to meet one of these two criteria:
- It has only one connection
Or
- The node's total connections minus the total leaves connected to said node is less than 2
Here is a visual example:
My current approach doesn't feel too efficient, I loop through all nodes and mark those nodes that meet criteria 1.
I loop again and again and mark every node that meets criteria 2. I do this until no further nodes are marked - then I exit the function.
Here is the logic:
int count;
do
{
count = 0;
foreach (node in allNodes)
{
//leaves is a hashset of marked nodes
if (leaves.Contains(node)) // already marked as leaf
continue;
if (IsLeaf(node))
{
leaves.Add(nodes);
count = 1;
}
}
} while (count > 0);
My IsLeaf
function has:
bool IsLeaf(node)
{
total = node.Connections;
// only has 1 or less connections, so it must be a leaf
if (total < 2)
return true;
//count all leaves connected to the node
totalLeaves = 0;
foreach (segment in node)
{
node2 = segment.GetOtherNode();
if (_leaves.Contains(node2))
totalLeaves ++;
}
//A node is a leaf when it has less than 2 connections to non-leaf nodes
return (total - totalLeaves ) < 2;
}
I am wondering if there is a more performant way to go about this other than looping all the nodes over and over until all leaves have been found?
N
has 5 connections to other nodes, and 4 of these other nodes are known to be leaf nodes, it must be the case then thatN
is also a leaf node - that is what criteria 2 basically means. You will find in the image the leaf node that has 5 connections fits this criteria. $\endgroup$