I’m trying to build a graph by adjacency list, which means I need a list for all the nodes, and inside every node class, I also need a data structure to hold all the adjacent nodes. Just wondering what the best structure would be to do this (a fast search for target node class). Would an array work?
Share
Here’s one way of building a directed graph in Ruby, where each node maintains references to its successors, but nodes can be referenced by name. First we’ll need a class for the nodes:
Each node maintains references to its successors. Not knowing what kind of operations you need, I haven’t defined any that actually do graph traversal, but each node having references to its successors makes traversing the graph trivial.
Now we’ll create a class to represent the entire graph:
This class keeps a hash of its nodes, keyed by name. This makes retrieval of a specific node easy.
Here’s an example of a graph containing a cycle: