Skip to content

Instantly share code, notes, and snippets.

@jharris-code
Last active January 8, 2019 20:51
Show Gist options
  • Save jharris-code/cb347d0f9b81d3d0e928a1a536149646 to your computer and use it in GitHub Desktop.
Save jharris-code/cb347d0f9b81d3d0e928a1a536149646 to your computer and use it in GitHub Desktop.
Graph Directed Adjacency Matrix
//Storage: O(V^2)
class Graph {
//O(V^2)
constructor(size){
this.vertices = [];
for(let i = 0; i < size; i++){
this.vertices.push([]);
for(let j = 0; j < size; j++){
this.vertices[i].push(false);
}
}
}
//O(V*2)
addVertex() {
let v = [];
for(let i = 0; i < this.vertices[0].length; i++){
v.push(false);
}
this.vertices.push(v);
for(let v of this.vertices.values()) {
v.push(false);
}
}
//O(V^2)
removeVertex(v) {
// O(V)
this.vertices.splice(v, 1);
// O(V^2)
for(let i = 0; i < this.vertices.length; i++){
this.vertices[i].splice(v, 1)
}
}
//O(1)
addEdge(v1, v2) {
this.vertices[v1][v2] = true;
}
//O(1)
removeEdge(v1, v2) {
this.vertices[v1][v2] = false;
}
}
let g = new Graph(2);
g.addVertex();
g.addVertex();
g.addEdge(1,3);
g.addEdge(2,0);
g.removeVertex(3);
// g.removeEdge(1,3);
console.log(g.vertices);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment