Data Structure to represent a DAG in Javascript

坚强是说给别人听的谎言 提交于 2019-12-05 13:03:33

you can use lists (arrays) in json. E.g. I could represent a simple directed graph as

{
  "NodeA": {"name": "NodeA", "adjacentTo": ["NodeB", "NodeC"]},
  "NodeB": {"name": "NodeB", "adjacentTo": ["NodeC", "NodeD"]},
  "NodeC": {"name": "NodeC", "adjacentTo": ["NodeA"]},
  "NodeD": {"name": "NodeD", "adjacentTo": []}
}

This would be the graph:

C
^^
| \
|  \
A -> B -> D

The name field really isn't needed, but you can associate any attributes you want with a node that way.

JavaScript objects must have string keys, but can store any type of value. Of course, the entire point in an id is to allow you to represent a complex type wirh a simple one.

var adjacentTo = {};
adjacentTo[node1.id] = [node2, node3]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!