SOURCE

// 构建图
function Graph() {
    this.verts = []; // 顶点
    this.edges = new Map(); // 边
}

// 添加顶点
Graph.prototype.addVert = function(v) {
    this.verts.push(v);
    this.edges.set(v, []);
}

// 添加边
Graph.prototype.addEdge = function(v1, v2) {
    this.edges.get(v1).push(v2);
    this.edges.get(v2).push(v1);
}

// 邻接表转邻接矩阵
Graph.prototype.toMat = function() {
    const n = this.verts.length;
    // 初始化矩阵距离为无穷
    const array = new Array(n).fill().map(()=>new Array(n).fill(Infinity))
    this.verts.forEach((item, index) => {
        this.edges.get(item).forEach((sItem, sIndex) => {
            array[index][sIndex] = 1;
        })
    })
    return array;
}

// 测试
let graph = new Graph();
let myVert = ['a', 'b', 'c', 'd', 'e', 'f'];
myVert.forEach(item => graph.addVert(item))
graph.addEdge('a', 'b')
graph.addEdge('a', 'c')
graph.addEdge('b', 'f')
graph.addEdge('f', 'e')
graph.addEdge('e', 'c')
let mat = graph.toMat()
console.log(mat)
console 命令行工具 X clear

                    
>
console