Skip to the code
cf.
+50 XP

#308 Fill the Number Grid Puzzle

hard

A puzzle widget shows an n × n grid, where n is 1, 4, or 9, split into boxes of size √n × √n. Each row, each column, and each box must hold every digit from 1 to n exactly once.

board is an array of n strings. Each character is a digit or . for an empty cell. Write solveGrid(board) that fills every empty cell and returns the board in the same format.

Fill the empty cells in reading order (row by row, left to right), trying smaller digits first, and return the first full board this finds. If the given digits already break a rule, or no filling works, return [].

Example 1

Input: board = ["1.3.","..1.",".1..","4..1"]
Output: ["1234","3412","2143","4321"]

Each row, column, and 2 × 2 box ends up with 1, 2, 3, and 4 exactly once.

Example 2

Input: board = ["11..","....","....","...."]
Output: []

Row 0 already has two 1s, so no filling can work.

Constraints

  • n is 1, 4, or 9.
  • board.length === n and every string has length n.
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).