# Why does this BFS shortest-path helper return a path that's one step too long?

**URL:** <https://forum.kirupa.com/t/why-does-this-bfs-shortest-path-helper-return-a-path-thats-one-step-too-long/680010>\
**Category:** web dev\
**Created:** [April 4, 2026, 11:00pm UTC](https://forum.kirupa.com/t/why-does-this-bfs-shortest-path-helper-return-a-path-thats-one-step-too-long/680010 "2026-04-04T23:00:10Z")\
**Posts on this page:** 2\
**Page:** 1

<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 4, 2026, 11:00pm UTC](https://forum.kirupa.com/t/why-does-this-bfs-shortest-path-helper-return-a-path-thats-one-step-too-long/680010/1 "2026-04-04T23:00:10Z")

</div>

I’m reconstructing the shortest path in an unweighted graph, but the returned path includes an extra node at the start for some cases. I suspect the parent tracking is off, not the BFS traversal itself. What am I missing?

```js
function path(graph, start, goal) {
  const q = [start], parent = { [start]: null };
  for (let i = 0; i < q.length; i++) {
    const node = q[i];
    if (node === goal) break;
    for (const nei of graph[node] || []) {
      if (!(nei in parent)) parent[nei] = node, q.push(nei);
    }
  }
  const out = [];
  for (let cur = goal; cur; cur = parent[parent[cur]]) out.push(cur);
  return out.reverse();
}

```

Hari

---

<div class="post-metadata">

**Author:** ![Ellen1979](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/ellen1979/32/31260_2.png) [@Ellen1979](https://forum.kirupa.com/u/Ellen1979)\
**Post date:** [April 4, 2026, 11:07pm UTC](https://forum.kirupa.com/t/why-does-this-bfs-shortest-path-helper-return-a-path-thats-one-step-too-long/680010/2 "2026-04-04T23:07:07Z")

</div>

@HariSeldon, the bug is in `cur = parent[parent[cur]]` since that walks two hops each time and can pull in the wrong start-side node when the chain gets sparse.

Ellen
