Skip to content

Instantly share code, notes, and snippets.

@jharris-code
Last active January 8, 2019 20:52
Show Gist options
  • Save jharris-code/56c8a55e0b95a7c2b1286175c0845c97 to your computer and use it in GitHub Desktop.
Save jharris-code/56c8a55e0b95a7c2b1286175c0845c97 to your computer and use it in GitHub Desktop.
Directed Graph Javascript Implementation
//Space Complexity: O(V + E)
class Graph {
constructor() {
this.vertices = new Map();
}
//O(V) time complexity of Map.prototype.set
addVertex(v) {
this.vertices.set(v, [])
}
//O(V) time complexity of Map.prototype.delete
removeVertex(v){
this.vertices.delete(v);
}
//O(V) time complexity of Map.prototype.get
addEdge(from, to) {
this.vertices.get(from).push(to);
//add this for an undirected graph:
//this.vertices.get(to).push(from);
}
//O(V + e) e = edges of given Vertex, V = time complexity of Map.prototype.get
removeEdge(from, to) {
let edges = [];
for(let e of this.vertices.get(from)) {
if(e !== to) {
edges.push(e)
}
}
this.vertices.get(from) = edges;
}
}
let g = new Graph();
g.addVertex('A');
g.addVertex('B');
g.addVertex('C');
g.addVertex('D');
g.addEdge('B', 'A')
g.addEdge('C', 'A')
// g.removeEdge('B', 'A')
g.removeVertex('A')
//prints "A"
console.log(g)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment