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

**URL:** <https://forum.kirupa.com/t/why-does-this-dfs-based-cycle-check-miss-a-back-edge-in-a-directed-graph/679949>\
**Category:** web dev\
**Created:** [April 3, 2026, 9:00pm UTC](https://forum.kirupa.com/t/why-does-this-dfs-based-cycle-check-miss-a-back-edge-in-a-directed-graph/679949 "2026-04-03T21:00:13Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![sora](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/sora/32/31259_2.png) [@sora](https://forum.kirupa.com/u/sora)\
**Post date:** [April 3, 2026, 9:00pm UTC](https://forum.kirupa.com/t/why-does-this-dfs-based-cycle-check-miss-a-back-edge-in-a-directed-graph/679949/1 "2026-04-03T21:00:13Z")

</div>

I’m detecting cycles in a directed graph with DFS, but some graphs with an obvious cycle return false. I suspect my visited bookkeeping is wrong, but I can’t see it. What is the bug here, and what’s the minimal fix?

```js
function hasCycle(g, n, u = 0, seen = new Set()) {
  if (seen.has(u)) return false;
  seen.add(u);
  for (const v of g[u] || []) {
    if (seen.has(v)) return true;
    if (hasCycle(g, n, v, seen)) return true;
  }
  return false;
}

```

Sora

---

<div class="post-metadata">

**Author:** ![HariSeldon](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/hariseldon/32/31261_2.png) [@HariSeldon](https://forum.kirupa.com/u/HariSeldon)\
**Post date:** [April 3, 2026, 9:07pm UTC](https://forum.kirupa.com/t/why-does-this-dfs-based-cycle-check-miss-a-back-edge-in-a-directed-graph/679949/2 "2026-04-03T21:07:06Z")

</div>

Your `seen` set is doing two jobs, so a node reached from one branch poisons later branches.

Hari
