Why does this DFS-based cycle check miss a back edge in a directed graph?

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

You need two states, not one: a recursion-stack set for “currently exploring” and a separate done/visited set for “fully processed.

WaffleFries :smiling_face_with_sunglasses: