1

我正在尝试在 JavaScript 中创建有向图数据结构。我希望图中的每个节点都是双向链接的,这样我就可以获得每个节点指向的链接列表,以及指向该节点的链接。每个节点都是一个包含 3 个元素的数组,如下所示:[["node that links to node a"], "node a", ["node that node a links to"]]

//The functions linkNodes and unlinkNodes should add and remove nodes links from the directed graph, respectively.
var nodes = new Object();

function linkNodes(a, b){
    //a should be a string, and b should be a string as well
    //create the node a, if it doesn't exist yet
    //create the node b, if it doesn't exist yet
    //link the node a to the node b
}

function unlinkNodes(){
    //unlink the nodes a and b, if a and b exist
    //create the node a, if it doesn't exist yet
}

function getNode(string){
    //get the node that corresponds to the string
    //if the string doesn't exist, then return false
}

jsfiddle: http: //jsfiddle.net/NTKZ9/1/ ​</p>

除了我在这里提出的方法之外,还有一种更简洁的方法可以在 JavaScript 中实现有向图吗?

4

1 回答 1

1

一种简洁的方法是将邻接矩阵存储在二维数组中。

于 2012-12-31T02:02:47.133 回答