I have a directed acyclic graph I’m trying to implement but I’m not sure what structure I can use. I keep believing that a tree or adjacency list would be viable but I am not given nodes to work with.
So in this case I tried to implement it using a 2d array, storing the priorities, in degrees and out degrees. However, I’m having problems figuring out how to insert an edge between two vertices and how I can check if a vertice is another vertice’s parent in this way.
When you say you’re “storing the priorities, in degrees and out degrees”, it suggests you don’t quite grok adjacency matrices. For an adjacency matrix M, vertices correspond to indices, and edges from v to u correspond to an entry in the matrix at Mvu (i.e. Mvu is the number of edges from v to u). The out-degree of a vertex v is ΣM*v; the in-degree is ΣMv*. If the matrix is in row-major order (Mrow, col), these correspond to the column and row sums, respectively.
“Priority” isn’t a vertex property in plain DAGs. If you have priorities associated with the vertices, your graph class should contain another data structure mapping vertices to priorities (probably a vector, since vertices are usually numbered consecutively). Better still, have two graph classes: a
DAGclass, and a childPriorityDAGclass that adds a priority property for nodes:If you’re ever going to have other types of graphs (undirected, cyclic), you can make a
Graphclass to be the parent ofDAG.Thus, to insert an edge, increment the value Mvu. If v is a parent of u, then there is an edge from v to u, so Mvu > 0.