I am trying to implement leetcode allpaths problem I have written the below solution, which is giving me the wrong output, I have purposefully, left the console statements for better debugging. Basically the variable path does not gets updated to [0] whenever the recursive call to findPath is done.
What am I missing here?
const allPaths = (edges) => {
const graph = buildAdjacencyListGraph(edges);
console.log(graph);
const result = []
let path = [0];
findPath(graph, 0, edges.length - 1, result, path)
}
const findPath = (graph, src, dest, result, path) => {
for (let neighbor of graph[src]) {
console.log('Path before push: ', path);
console.log('Result before push: ', result);
path.push(neighbor);
console.log('Path: ', path);
console.log('Result: ', result);
console.log('Neighbor', neighbor);
console.log('Destination: ', dest);
console.log('Is neighbor and dest equal?: ', dest === neighbor);
if (neighbor === dest) {
result.push([...path])
console.log('Result after equal: ', result);
path = [0];
console.log('Path after equal: ', path);
continue;
}
findPath(graph, neighbor, dest, result, path);
}
}
const buildAdjacencyListGraph = (edges) => {
const graph = {};
for (let [i, edge] of edges.entries()) {
graph[i] = edge;
}
return graph;
}
const graph = [[4,3,1],[3,2,4],[3],[4],[]]
allPaths(graph)