How do you store a Directed Acyclic Graph (DAG) as JSON?

Label each node and make an edge list. That is, for each node store the nodes that it has edges to, for example:

{
  "a": [ "b", "c", "d" ],
  "b": [ "d" ],
  "c": [ "d" ],
  "d": [ ]
}

You can store many kinds of graphs this way, not just DAGs, so you will need to post-process it to make sure that it has no loops. Just pick a node, DFS, if you see any node more than once it is not a DAG. Then remove all of the nodes you just saw and repeat with any remaining nodes. Do this until you find a loop or you’ve removed all of the nodes, in the latter case the graph is a DAG.

Note that this does not store parent nodes, since that is redundant information. You can generate those after loading the graph if you need that data.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)