Here's a complete implementation of an adjacency matrix
.
xxxxxxxxxx
38
console.log(g.toString());
class Graph {
constructor(numVertices) {
this.numVertices = numVertices;
this.adjMatrix = Array.from({ length: numVertices }, () => Array(numVertices).fill(false));
}
​
addEdge(i, j) {
this.adjMatrix[i][j] = true;
this.adjMatrix[j][i] = true;
}
​
removeEdge(i, j) {
this.adjMatrix[i][j] = false;
this.adjMatrix[j][i] = false;
}
​
toString() {
let s = "";
for (let i = 0; i < this.numVertices; i++) {
s += i + ": ";
for (const j of this.adjMatrix[i]) {
s += (j ? 1 : 0) + " ";
}
s += "\n";
}
return s;
}
}
​
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment