DEV Community

Seed Map
Seed Map

Posted on

Spiral search: checking the nearest grid cells first in JavaScript

When you look for a structure or biome near a point, you want to check the closest cells first and stop as soon as you find a match. A plain double loop over a square scans row by row, so it may test a far corner before a cell right next to the start. A spiral search fixes that: it walks outward ring by ring from the centre. Here is a small, allocation-free version in JavaScript, with a Minecraft-style example.

The idea

Starting at (0, 0), visit cells in this order: the centre, then the 8 cells of ring 1, then the 16 cells of ring 2, and so on. Every cell in ring r has a Chebyshev distance of r from the centre (max of |dx|, |dz|), so you always finish nearer rings before farther ones.

A generator for spiral coordinates

// Yields [dx, dz] offsets ring by ring, up to maxRadius.
function* spiral(maxRadius) {
  yield [0, 0];
  for (let r = 1; r <= maxRadius; r++) {
    // top edge, left to right
    for (let x = -r; x <= r; x++) yield [x, -r];
    // right edge, top to bottom (corners already done)
    for (let z = -r + 1; z <= r; z++) yield [r, z];
    // bottom edge, right to left
    for (let x = r - 1; x >= -r; x--) yield [x, r];
    // left edge, bottom to top
    for (let z = r - 1; z > -r; z--) yield [-r, z];
  }
}
Enter fullscreen mode Exit fullscreen mode

Each ring yields 8 * r cells, and nothing is visited twice. Because it is a generator, it does not build an array, so a radius of a few thousand costs no memory up front.

Using it to find the nearest match

function findNearest(centerX, centerZ, maxRadius, test) {
  for (const [dx, dz] of spiral(maxRadius)) {
    const x = centerX + dx, z = centerZ + dz;
    if (test(x, z)) return { x, z, ring: Math.max(Math.abs(dx), Math.abs(dz)) };
  }
  return null;
}

// Example: search 32x32-chunk regions (512 blocks) around the player's region
// for one that a (hypothetical) predicate says contains a structure.
const playerRegion = { x: Math.floor(1200 / 512), z: Math.floor(-830 / 512) };
const hit = findNearest(playerRegion.x, playerRegion.z, 20, (rx, rz) => hasStructure(rx, rz));
console.log(hit); // e.g. { x: 4, z: -1, ring: 2 }
Enter fullscreen mode Exit fullscreen mode

Ring order is not exact distance order

Within one ring, the corner cells are farther away in straight-line (Euclidean) distance than the edge midpoints. If you need the truly nearest hit, keep searching past the first match until you reach the ring equal to the best match's distance, and pick the smallest Euclidean distance among the candidates:

function findNearestEuclid(cx, cz, maxRadius, test) {
  let best = null, stopAt = Infinity;
  for (const [dx, dz] of spiral(maxRadius)) {
    const ring = Math.max(Math.abs(dx), Math.abs(dz));
    if (ring > stopAt) break;
    if (test(cx + dx, cz + dz)) {
      const d2 = dx * dx + dz * dz;
      if (!best || d2 < best.d2) best = { x: cx + dx, z: cz + dz, d2 };
      stopAt = Math.min(stopAt, Math.ceil(Math.sqrt(d2)));
    }
  }
  return best;
}
Enter fullscreen mode Exit fullscreen mode

A match in ring r is at most r * sqrt(2) away, and any closer match must have a ring number no larger than its own distance, so it lies within ring ceil(r * sqrt(2)). Stopping there guarantees the result.

Where this shows up

Spiral search is the core of "find nearest" features in map tools: nearest village, nearest biome of a type, nearest chunk that meets a condition. If you just want the answer for a real world rather than code, the structure finder on Minecraft Seed Map lists the nearest structures for a seed and position.

Top comments (0)