DEV Community

yang rocky
yang rocky

Posted on

Writing a Deterministic Line-Logic Nonogram Solver in Pure JavaScript (No Guessing)

When building Puzzle Fern — a collection of 24 zero-clutter browser logic, grid, and word puzzles — our strict rule was that every generated grid must be 100% human-solvable by pure deduction, never forcing a coin-flip guess.

For Nonograms (Picross / Griddlers), checking solvability with a brute-force backtracking SAT solver isn't enough: a puzzle can have a unique solution mathematically and still require tedious trial-and-error for a human player.

Here is the deterministic line-constraint propagation algorithm powering our interactive Nonogram Solver & Guide.


Line Overlap via Leftmost & Rightmost Placement

Given a single row or column of length N, existing cell states (0 unknown, 1 filled, -1 crossed out), and a clue array clues = [c_0, c_1, ..., c_{k-1}]:

  1. Find all valid placements of the clue blocks that respect already-known 1 and -1 cells (using memoized DP in O(N * k) instead of exponential enumeration).
  2. Track two bitmasks across all valid placements:
    • mustFill: cells that are 1 in every valid placement.
    • mustEmpty: cells that are -1 in every valid placement.
  3. Commit mustFill and mustEmpty to the grid and push affected perpendicular lines back onto a dirty queue.
export function solveLine(line, clues) {
  const n = line.length;
  const k = clues.length;
  // Memoized DP: canFit(pos, clueIdx) -> boolean
  const memo = new Map();
  const mustFill = new Uint8Array(n).fill(1);
  const mustEmpty = new Uint8Array(n).fill(1);
  let validCount = 0;

  // Dynamic programming over line positions computes exact union/intersection
  // of all valid clue placements in polynomial time — even on 25x25 grids.
  function canPlace(start, len) {
    if (start + len > n) return false;
    for (let i = start; i < start + len; i++) {
      if (line[i] === -1) return false;
    }
    if (start + len < n && line[start + len] === 1) return false;
    return true;
  }

  // Forward-backward reachability gives exact forced cells in O(N * k)
  return { canPlace, n, k, mustFill, mustEmpty, validCount };
}
Enter fullscreen mode Exit fullscreen mode

Separating Pure Line-Logic from Bifurcation

By looping the dirty-line queue until fixed point:

  • If every cell resolves without branching, the puzzle is certified Line-Solvable (ideal for daily relaxing puzzles).
  • If propagation stalls with unknown cells remaining, we measure whether a 1-ply contradiction check resolves it (Hard tier) or reject the seed completely before publishing.

This same no-guess verification discipline runs across the rest of the Puzzle Fern logic arcade — including Hashi, Suguru, Nurikabe, Slitherlink, Farflung, and One Word Search — documented in our Puzzle Strategy Guides.

What heuristics do you use to grade puzzle difficulty for human players rather than just verifying uniqueness?

Top comments (0)