A have a set of objects. Each object contains a list of other objects to which it is connected, but not all objects are connected to every other object. I’m trying to visit each object connected to a specific starting object. The most obvious way to accomplish this is this:
- Put each object connected to the starting point into a queue
- For each object in the queue:
- Perform whatever operation on this object
- Add this object to a list of visited objects
- Check if each object connected to this object if in this visited list, if not, add it to the queue
Is there a better way that doesn’t involve storing a list of every visited object?
Given the data-structure you describe (any object can connect to any other) I don’t think you have a choice other than to keep an already-visited list. If your objects were in a hierarchical tree structure, then a recursive tree walking algorithm could be implemented to do what you want.
In your structure of peer-connected objects, any algorithm that tries to do away with an already-visited list will run the risk of going into infinite loops for circular references. I suppose you could create a ‘visited’ flag in the objects themselves, clearing them all before some algorithm runs, but this seems more clunky than the list method (and is inherently less thread-able).