I have a graph which I traverse using a typical visitor pattern. I’ve run into an issue where I need to know if the node being visited has already been visited during the current traversal.
I’ve developed a solution that I think would work, but it would require creating and destroying node “flags” during/after the graph traversal.
That is, as each node is visited, a flag object pointer member in the node would be checked. If it’s NULL, the visitor would create a flag object and assign it to the node’s flag object pointer. Then, the visitor would push a reference to the flag pointer member into it’s own internal list ( of pointers to flag object pointers, of course ). Otherwise, if the node’s flag object pointer isn’t NULL, the visitor stops traversal on that node.
Cleanup would then be a matter of popping / deleting the flag objects from the visitor’s list after the traversal is complete, and reassigning each node flag pointer in the list to NULL.
It’s a bit involved and strikes me as being potentially leak-prone, but I’ve no better ideas…
Thoughts?
As an addendum, the purpose is to list out in a text console the structure of a tree. If I have several nodes, however, which are parents of a common subgraph, I want to list that subgraph only once and then refer to it using some nomenclature like “[ Subnode1…]” everywhere else.
I mean this for two purposes –
- I don’t want to constantly dump the same data to the screen several times
- I want a way to visually indicate where a node is simply referencing another part of the existing graph.
As such, setting / clearing a bool as each node is traversed defeats the purpose. I don’t want to clear any bools until the root node traversal is complete (i.e., the very last step of the traversal). And, of course, by that point, the question becomes, how do I get all of those flags to reset themselves without re-visiting the entire graph?
Anyway, I’d rather not traverse the graph twice (once to do the work and again to clear flags) or constantly iterate a list each time I visit a node to determine if I’ve visited it before. The graph isn’t large, but it’s part of a render subsystem and the traversal occurs between frames, so I want it to make sure it runs quickly…
Typical Visitor pattern for a single Node class:
The above defined the generic implementation of a visitor for a graph.
The thing about graphs is that they usually only have one node type so that makes the visitor interface very easy. Now a simple implementation of the visitor interface that makes sure we don’t processes nodes more than once.