Social feed~45 min2s · 256 MBtarget exponential in the worst case, tiny with the fewest-options rule time, O(81) spaceclassic twin: lc-37backtracking
A social app posts a number puzzle every day. The board is nine rows of nine cells. Each cell holds a digit from 1 to 9, or is empty. The digits must follow three rules: no repeat in a row, in a column, or in a three by three box.
A good daily puzzle has exactly one way to fill the empty cells. Before posting, the team counts the ways to complete the board. The count stops at two, because two ways are already too many.
Write count_solutions(board).
board is a list of 9 strings of 9 characters. A character is 1 to 9 for a given digit, or . for an empty cell.0, 1, or 2 for two or more.Input: board = ["53.678912","6721.5348","198342567","859761423",".26853791","713924856","96153.284","287419635","34528617."]
Output: 1Five cells are empty. The solution marks every given digit in a bit set for its row, column and box. It always fills the empty cell with the fewest possible digits.
| Step | Cell picked (row, column) | Possible digits | Digit placed |
|---|---|---|---|
| 1 | (0, 2) | 4 | 4 |
| 2 | (1, 4) | 9 | 9 |
| 3 | (4, 0) | 4 | 4 |
| 4 | (6, 5) | 7 | 7 |
| 5 | (8, 8) | 9 | 9 |
Every cell had one option, so the board has one completion. Rows and columns are counted from 0.
Input: board = ["534..8912","672195348","198342567","859..1423","426853791","713924856","961537284","287419635","345286179"]
Output: 2Four cells are empty, in two rows and two columns. The digits 6 and 7 can sit either way round, so there are two completions.
Input: board = ["55.......",".........",".........",".........",".........",".........",".........",".........","........."]
Output: 0The first row already holds two 5s, so no completion exists.
board has 9 rows of 9 characters from 1 to 9 and .An empty board has 9 choices for each of 81 cells, which is 9 to the power 81 boards. Even the rules prune most of them, and a search in reading order can still take billions of steps on some puzzles. The order in which you fill the cells matters a great deal.