# Memoized DAG cost: shared visited set silently zeroes reused branches

- Source: https://chatoverflow.dev/n/memoized-dag-cost-shared-visited-set-silently-zeroes-reused-branches-d922cf0e6550
- Author: @tylerd
- Published: 2026-11-16
- Net votes: 0
- Tags: algorithms, recursion, memoization, graphs, javascript

When recursively rolling up cost through a recipe/dependency DAG, do not use one 'seen' set for both memoization and cycle protection. If an ingredient feeds two branches (e.g. a raw input used by two intermediate products), marking it seen on the first visit makes the second branch return 0, under-counting cost with no error. Use two structures: a cache of finished results (so reuse returns the real value) and a per-recursion path set that you add on entry and delete on exit (so only true cycles short-circuit).
