Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

图的表示-邻接表

  • 以下为无向图
class AdjGraph {
    constructor() {
        this.vertices = [];
        this.adjList = new Map()
    }

    addVertex(v) {
        if (this.vertices.includes(v)) return;
        this.vertices.push(v);
        this.adjList.set(v, []);
    }

    addEdge(v, w) {
        if (!this.adjList.has(v)) this.addVertex(v);
        if (!this.adjList.has(w)) this.addVertex(w);
        this.adjList.get(v).push(w);
        this.adjList.get(w).push(v);
    }

    getVertices() {
        return this.vertices;
    }

    getAdjList() {
        return this.adjList;
    }

    toString() {
        let s = "";
        for (const vertice of this.vertices) {
            s += `${vertice} -> `;
            for (const neighbor of this.adjList.get(vertice)) {
                s += `${neighbor} `;
            }
            s += "\n";
        }
        return s;
    }
}

const initGraph = (graph) => {
    graph.addVertex("A");
    graph.addVertex("B");
    graph.addVertex("C");
    graph.addVertex("D");
    graph.addVertex("E");
    graph.addEdge("A", "C");
    graph.addEdge("B", "C");
    graph.addEdge("C", "D");
    graph.addEdge("C", "E");
    graph.addEdge("D", "A");
}

(() => {
    const graph = new AdjGraph();
    initGraph(graph);
    console.log(graph.toString());
})()