JSFiddle - React, Tailwind, and code Playground

by jrab227

JavaScript

let graph = {
	'0': [1, 2],
  '1': [3],
  '2': [4],
  '3': [5],
  '4': [5, 6],
  '5': [],
  '6': []
};

function findPaths(path, index, target, seen) {

	//Update the memoization
	seen[index] = true;
  
  //If we've found a complete path, return a list of no paths
	if (index === target) {
  	return [path + ',' + index];
  }
  
  //If we've hit a node with no edges, return a list of no paths
  if (graph[index].length == 0) {
  	return [];
  }
  
  //Otherwise produce a list of subpaths starting at the current node and ending at the target
	let paths = [];
	for(var connectingNode of graph[index]) {
  	paths.push( findPaths(path + ',' + index, connectingNode, target, seen));
  }
  
  //Then join the paths into a single list of paths
  return [].concat.apply([], paths);
}

console.log(findPaths('', 0, 5, {}));