# javascript – Bad performance of a Graph Algorithm

I implemented a solution for the problem below, but its performance is not good.
I know I can find the solution online, I’m trying to understand what is causing the bad performance in `my code`

Problem:
You have an undirected, connected graph of $$n$$ nodes labeled from $$0$$ to $$n – 1$$. You are given an array graph where $$graph(i)$$ is a list of all the nodes connected with node $$i$$ by an edge.

Return the length of the shortest path that visits every node. You may start and stop at any node, you may revisit nodes multiple times, and you may reuse edges.

Test Cases:

``````Input: graph = ((1,2,3),(0),(0),(0))
Output: 4
Explanation: One possible path is (1,0,2,0,3)
``````
``````Input: graph = ((1),(0,2,4),(1,3,4),(2),(1,2))
Output: 4
Explanation: One possible path is (0,1,4,2,3)
``````

My code:

``````var shortestPathLength = function(graph) {
const totalNodes = graph.length;
let output = Infinity;

const smallestPathFromNode = (node) => {
let count = Infinity;
let queue = ();
queue.push((node, new Set(), 0));
while(queue.length > 0) {
const (curNode, visited, moves) = queue.shift();
if(visited.size === totalNodes) {
count = Math.min(count, moves)
continue;
}
if(moves > count || moves > output)
continue;
const nextNodes = graph(curNode);
for(const nextN of nextNodes) {
const newVisited = new Set(visited);
queue.push((nextN,newVisited,moves+1));
}
}
return count-1;
}

for(let i=0; i<graph.length; i++) {
output = Math.min(output, smallestPathFromNode(i))
}

return output === Infinity ? 0: output;
};
``````

Test case with a bad performance (takes too long to execute):

``````((2,3),(7),(0,6),(0,4,7),(3,8),(7),(2),(5,3,1),(4))
``````

Posted on Categories Articles