# Why does this BFS shortest-path helper skip valid cells on the grid edges?

**URL:** <https://forum.kirupa.com/t/why-does-this-bfs-shortest-path-helper-skip-valid-cells-on-the-grid-edges/679972>\
**Category:** web dev\
**Created:** [April 4, 2026, 7:00am UTC](https://forum.kirupa.com/t/why-does-this-bfs-shortest-path-helper-skip-valid-cells-on-the-grid-edges/679972 "2026-04-04T07:00:15Z")\
**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 4, 2026, 7:00am UTC](https://forum.kirupa.com/t/why-does-this-bfs-shortest-path-helper-skip-valid-cells-on-the-grid-edges/679972/1 "2026-04-04T07:00:15Z")

</div>

I’m debugging a BFS for the shortest path in a 2D grid with 0=free and 1=wall. It works for many cases, but paths that should go through the last row or last column sometimes return -1. I suspect my bounds check is wrong, but I can’t see it.

```js
function shortest(grid, sr, sc, tr, tc) {
  const q = [[sr, sc, 0]], seen = new Set([`${sr},${sc}`]);
  const dirs = [[1,0],[-1,0],[0,1],[0,-1]];
  while (q.length) {
    const [r, c, d] = q.shift();
    if (r === tr && c === tc) return d;
    for (const [dr, dc] of dirs) {
      const nr = r + dr, nc = c + dc;
      if (nr < 0 || nc < 0 || nr >= grid.length - 1 || nc >= grid[0].length - 1) continue;
      if (grid[nr][nc] === 1 || seen.has(`${nr},${nc}`)) continue;
      seen.add(`${nr},${nc}`); q.push([nr, nc, d + 1]);
    }
  }
  return -1;
}

```

What exactly is wrong here, and is there a cleaner way to structure the boundary check?

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 4, 2026, 7:14am UTC](https://forum.kirupa.com/t/why-does-this-bfs-shortest-path-helper-skip-valid-cells-on-the-grid-edges/679972/2 "2026-04-04T07:14:07Z")

</div>

Your upper bound is off by one, because `nr >= grid.length - 1` and `nc >= grid[0].length - 1` reject the entire last row and last column, so the check should be against `grid.length` and `grid[0].length` instead.

Hari
