Under construction

Still being built. Things may change

Sudoku

Time limit1sMemory limit256 MB

Summary
Solve a standard 9x9 sudoku puzzle by filling empty cells so every row, column, and 3x3 box contains digits 1 through 9, using backtracking search.
Level

Medium6 of 10

Topics
Backtracking, Matrix, Brute force
Solved
No attempts yet

Problem

Sudoku is a puzzle played on a 9x9 board. Some cells already contain a digit from 1 through 9, and the remaining empty cells must be filled according to the rules.

Fill the empty cells using these rules.

  1. Each row must contain every digit from 1 through 9 exactly once.
  2. Each column must contain every digit from 1 through 9 exactly once.
  3. Each 3x3 square marked by the thick lines must also contain every digit from 1 through 9 exactly once.

In the first picture, the first row already contains every digit from 2 through 9, so the empty cell in that row must be 1.

In the upper middle 3x3 square, every digit except 3 is already present, so the empty middle cell must be 3.

Filling the remaining cells in this way gives the completed board below.

Given the Sudoku board at the start of the game, write a program that completes the board and prints the final state.

Input

Nine lines are given. Each line contains 9 integers separated by spaces, describing one row of the Sudoku board. Filled cells contain a digit from 1 through 9, and empty cells contain 0. Inputs that cannot be completed according to the rules are not given.

Output

Print the completed Sudoku board in nine lines. Each line must contain 9 digits separated by spaces.

If there is more than one valid completion, print any one of them.

Constraints

Every input board can be completed according to the Sudoku rules.

Reference execution times are as follows.

  • C++14: 80ms
  • Java: 292ms
  • PyPy3: 1172ms

Examples1

  1. Example 1

    Input
    0 3 5 4 6 9 2 7 8
    7 8 2 1 0 5 6 0 9
    0 6 0 2 7 8 1 3 5
    3 2 1 0 4 6 8 9 7
    8 0 4 9 1 3 5 0 6
    5 9 6 8 2 0 4 1 3
    9 1 7 6 5 2 0 8 0
    6 0 3 7 0 1 9 5 2
    2 5 8 3 9 4 7 6 0
    
    Expected output
    1 3 5 4 6 9 2 7 8
    7 8 2 1 3 5 6 4 9
    4 6 9 2 7 8 1 3 5
    3 2 1 5 4 6 8 9 7
    8 7 4 9 1 3 5 2 6
    5 9 6 8 2 7 4 1 3
    9 1 7 6 5 2 3 8 4
    6 4 3 7 8 1 9 5 2
    2 5 8 3 9 4 7 6 1