Graph类:

function Graph(v) { this.vertices = v; this.edges = 0; this.adj = [];
//初始化adj for (var i = 0; i < this.vertices; ++i) { this.adj[i] = []; this.adj[i].push(""); } this.addEdge = addEdge; this.showGraph = showGraph; } //插入边
//邻接表 function addEdge(v, w) { this.adj[v].push(w); this.adj[w].push(v);
this.edges++;
}
/*邻接矩阵存储......*/


//输出边 function showGraph() { for (var i = 0; i < this.vertices; ++i) { putstr(i + " -> "); for (var j = 0; j < this.vertices; ++j ) { if (this.adj[i][j] != undefined) { putstr(this.adj[i][j] + ' '); } } print(); } }

/*
vertices 节点数, Graph(v)传入的v是节点数
edges 边数
adj (邻接表数组,这里使用了法一,一个二维数组,每个节点的临界节点数组组成的数组)
*/

  

以下测试程序演示了 Graph 类的用法:
load("Graph.js"); 

g = new Graph(5); 

g.addEdge(0,1); 

g.addEdge(0,2); 

g.addEdge(1,3); 

g.addEdge(2,4); 

g.showGraph();
程序的输出结果为:
0 -> 1 2 

1 -> 0 3 

2 -> 0 4 

3 -> 1 

4 -> 2

来自:《数据结构与算法JavaScript描述》

原文地址:https://www.cnblogs.com/Longhua-0/p/9573053.html