classGraph{constructor(isDirected =false){// 接收参数来表示图是否有向this.isDirected = isDirected;// 使用数组来存储图中所有顶点的名字this.vertices =[];// 用字典来存储邻接表this.adjList =newMap();}// 向图中添加新的顶点addVertex(v){if(!this.vertices.includes(v)){// 将顶点添加到顶点列表中this.vertices.push(v);// 设置顶点 v 作为键对应的字典值为一个空数组this.adjList.set(v,[]);}}// 添加顶点间的边addEdge(v, w){// 如果顶点 v 或 w 不存在于图中,要将它们加入顶点列表if(!this.adjList.get(v)){this.addVertex(v);}if(!this.adjList.get(w)){this.addVertex(w);}// 通过将 w 加入到 v 的邻接表中,添加了一条自顶点 v 到顶点 w 的边this.adjList.get(v).push(w);// 若是有向图,则需要添加自顶点 w 到顶点 v 的边if(!this.isDirected){this.adjList.get(w).push(v);}}// 返回顶点列表getVertices(){returnthis.vertices;}// 返回邻接表getAdjList(){returnthis.adjList;}}
module.exports = Graph;
1-2. 实现图的创建
const Graph =require("./graph");const graph =newGraph();var myVertices =['A','B','C','D','E','F','G','H','I'];for(let i =0; i < myVertices.length; i++){
graph.addVertex(myVertices[i]);}
graph.addEdge('A','B');
graph.addEdge('A','C');
graph.addEdge('A','D');
graph.addEdge('C','D');
graph.addEdge('C','G');
graph.addEdge('D','G');
graph.addEdge('D','H');
graph.addEdge('B','E');
graph.addEdge('B','F');
graph.addEdge('E','I');const vertices = graph.getVertices();const adjList = graph.getAdjList();let s ="";
vertices.forEach(element =>{
s +=`${element} -> `;const lists = adjList.get(element);
lists.forEach(element =>{
s +=`${element} `});
s +="\n";});
console.log(s)