Skip to content

Instantly share code, notes, and snippets.

@cauefcr
Last active April 23, 2018 18:22
Show Gist options
  • Save cauefcr/2946a51eaefa3ac6083b90730679cc7b to your computer and use it in GitHub Desktop.
Save cauefcr/2946a51eaefa3ac6083b90730679cc7b to your computer and use it in GitHub Desktop.
generate all paths from a DAG
// https://bl.ocks.org/cjrd/raw/6863459/
// draw your DAG, download the json
// authors: Cauê Felchar, José Henrique Roquette
g = <your json>
dag_all_paths = function(g,start,end){
dict = new Map();
dictname = new Map();
for(let i = 0; i < g.nodes.length; i++){
dict[g.nodes[i].id] = i;
dictname[g.nodes[i].title] = i;
}
g.look = function(e){
return g.nodes[e];
};
g.name = function(e){
return g.look(e).title;
};
g.name2index = function(n){
return dictname[n];
}
g.vizinho = function(){
g.viz = [];
for(let i = 0; i < g.nodes.length; i++){
g.viz.push([]);
}
for(let i = 0; i < g.edges.length; i++){
g.viz[dict[g.edges[i].source]].push(dict[g.edges[i].target]);
}
};
path = [];
function caminhos(grafo,inicial,ultimo,estado){
estado.push(inicial);
if(grafo.viz[inicial].length === 0){
path.push(estado.map(g.name));
}
grafo.viz[inicial].forEach(function(el){
caminhos(grafo,el,ultimo,estado.slice(0));
});
}
g.vizinho();
caminhos(g,g.name2index(start),g.name2index(end),[]);
return path;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment