Skip to content

Instantly share code, notes, and snippets.

@trykhov
Created June 8, 2020 23:12
Show Gist options
  • Save trykhov/03ee11e56dd0620b34a5d70151c6b033 to your computer and use it in GitHub Desktop.
Save trykhov/03ee11e56dd0620b34a5d70151c6b033 to your computer and use it in GitHub Desktop.
// assuming our adjacency matrix is {A: [B, C, D], B:[D, E], ...}
// assuming that our vertices have the following properties:
// 1. (boolean) visited
// ASSUME graph is a DAG
function topSort(adj) {
// get the number of vertices in the DAG
let numV = Object.keys(adj).length;
// initialize resulting array
let res = Array.new(numV).fill(null);
// get the last index of the array
let openIdx = res.length - 1;
// have a dfs helper function
function dfs(vertex) {
// base case
// if the vertex has already been processed, just ignore it
if(v.visited) return;
// get the neighbors
let neighbors = adj[vertex];
// loop through the neighbors
for(let v of neighbors) {
// do a DFS if the vertex hasn't been visited
if(!v.visited) dfs(v);
}
// mark the vertex as visited
vertex.visited = true;
// add the vertex to the rightmost open spot in the array
res[openIdx] = vertex;
// move the index to the next open spot on the left
openIdx -= 1;
return;
}
// get the vertices
let vertices = Object.keys(adj);
// do a DFS on all the vertices
for(let v of vertices) {
if(!v.visited) dfs(v);
}
// return the resulting array
return res;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment