I’m implementing cycle detection for a directed graph with DFS, but this returns false for some graphs that clearly have a cycle. I think my visited logic is wrong, but I’m not seeing it.
function hasCycle(g, n, seen = new Set()) {
if (seen.has(n)) return false;
seen.add(n);
for (const next of g[n] || []) {
if (hasCycle(g, next, seen)) return true;
}
seen.delete(n);
return false;
}
const g = { A: ['B'], B: ['C'], C: ['A'] };
console.log(hasCycle(g, 'A'));
What state should I track to correctly detect cycles in directed graphs?
Hari