Skip to content

Instantly share code, notes, and snippets.

@colibie
Last active May 26, 2020 21:04
Show Gist options
  • Save colibie/037c618ef0aa4a3bed94cd1e5b544aa0 to your computer and use it in GitHub Desktop.
Save colibie/037c618ef0aa4a3bed94cd1e5b544aa0 to your computer and use it in GitHub Desktop.
the data structure for a directed graph
export class Digraph { // exported so we can use it in topological sort
constructor(v) {
this.v = v; // initialize the number of vertices
this.e = 0; // and edges
this.adj = {}; // this object contains thevertices connected to each vertex.
}
addEdge(v, w) {
if (!adj[v]) adj[v] = []; // check if the vertex already exist, if not, created it
adj[v].push(w); // push the connecting edge vertex to its array of vertices
e++; // increment the number of edges
}
adj(v) { return adj[v]; } // return all the vertices connected to v
V() { return v; } // return number of vertices
E() { return e; } // return number of edges
/**
* Reverses the graph direction
* For directed graphs only
* @param g
* @return reversed graph
*/
reverse() {
Digraph rev = new Digraph(v);
// for each of the vertices, get the other vertices connected to it and addEdge in // reverse order
for (let i = 0; i < v; i++) {
for (let v of adj(i)) {
rev.addEdge(v, i);
}
}
return rev;
}
run() {
Digraph test = new Digraph(4);
test.addEdge(0, 1);
test.addEdge(1, 2);
test.addEdge(1, 3);
test.addEdge(3, 0);
console.log(test.E() + " edges"); // 4
console.log(test.V() + " vertices"); // 4
for (let v of test.adj(1)) {
console.log("1->" + v); // 2 3
}
Digraph revTest = test.reverse();
for (let v of revTest.adj(1)) {
console.log("1->" + v); // 0
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment