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 every empty square with a digit from 1 to 6 so that each row, each column and each box contains every digit exactly once.

The puzzle editor wants a program that fills in a grid before it goes to print. It must also catch broken puzzles: a typo in the clues can make a grid impossible, and those must not reach the readers.

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 (row 1, column 4), so row 0's 6 must sit in the top-left box, and the only empty square there in row 0 is column 0. Reasoning like this, or plain trial and error, fills the rest. This puzzle has exactly one solution.

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

Look at the top-left square. Its row already has 2 and 3, its column has 4 and 5, and its box has 6 and 1. No digit is left for it, so the puzzle cannot be completed.

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. Even at a billion grids per second it would take well over a century.

The opposite shortcut, putting the first digit that fits in each square and never going back, is fast but often gets stuck: an early guess that looks fine can leave a later square with no digit at all.

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