Puzzle Page Mini Grid

HardbacktrackingAlso known as Sudoku Solver (6 × 6)

A weekend newspaper runs a mini number puzzle: a 6 × 6 grid split into six boxes of 2 rows by 3 columns. Readers fill each empty square with a digit from 1 to 6 so every row, column and box holds each digit exactly once.

The editor wants a program that fills in a grid before it is printed. The program must also catch broken puzzles, because a typo in the clues can make a grid impossible to complete.

Your task

Write solvePuzzle(grid). grid is a list of 6 strings of length 6. Each character is a digit '1' to '6' (a printed clue) or '.' (an empty square). The boxes are rows 0–1, 2–3 and 4–5, each split into columns 0–2 and 3–5. Square (r, c) is in box ⌊r/2⌋ × 2 + ⌊c/3⌋.

Return the completed grid as 6 strings of digits, keeping every clue where it is. If the puzzle has several solutions, return any one. If it has none, including when the clues themselves repeat a digit in a row, column or box, return an empty list.

solvePuzzle(grid: string[]) → string[] Several answers can be correct; any valid one is accepted.

Examples

Example 1
Input
grid = [".23...", "..136.", ".6..1.", "....2.", ".1.5..", ".3.2.."]
Output
["623154", "451362", "362415", "145623", "214536", "536241"]
Why

Row 0 needs a 6. The top-right box already has a 6 at row 1, column 4, so the 6 in row 0 must go in the top-left box, and the only empty square there in row 0 is column 0. Reasoning like this, or trial and error, fills in the rest, and this puzzle has exactly one solution.

Example 2
Input
grid = ["...23.", ".61...", "4.....", "5.....", "......", "......"]
Output
[]
Why

The top-left square's row already contains 2 and 3, its column contains 4 and 5, and its box contains 6 and 1. No digit is left for that square.

Constraints

  • grid has 6 rows, each a string of 6 characters from '1'–'6' and '.'.
  • Any valid completed grid is accepted.
  • Return [] when no completion exists.
Start with brute force

Try every combination of digits in the empty squares and check the full grid each time. With 24 empty squares that is 624, about 4.7 × 1018 grids, which would take well over a century at a billion grids per second.

The opposite shortcut is to take the first digit that fits and never go back. It is fast but often gets stuck, because an early guess that looks fine can leave a later square with no digit.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code