This page is still under construction.

Parts of this page are still being built. What you see may change.

Sudoku (Hard)

Interview

Time limit0.1sMemory limit512 MB

Summary
Fill a 9x9 Sudoku grid so every row, column, and 3x3 box holds the digits 1 to 9 exactly once.
Level

Medium6 of 10

Topics
Backtracking, Implementation, Recursion, Matrix
Solved
No attempts yet

Problem

Sudoku comes from the "Latin square" puzzle invented by an 18th-century Swiss mathematician, and it is very popular today. The game is played on a square board made of 81 small cells, 9 across and 9 down, as shown below. Before the game starts, some cells already contain one of the digits from 1 to 9.

The remaining empty cells are filled as follows.

  1. Each row and each column must contain the digits 1 to 9 exactly once.
  2. Each 3x3 square separated by the thick lines must also contain the digits 1 to 9 exactly once.

In the example above, the first row already contains 2 to 9, so the empty cell in the first row must contain 1.

Also, the 3x3 square in the upper middle already contains every digit except 3, so the empty cell in its middle must contain 3.

Filling the empty cells one after another this way gives the final result below.

Given the digits written on the Sudoku board before the game starts, write a program that prints the final board with every empty cell filled.

Input

Nine lines are given. Each line contains the 9 digits written in one row of the Sudoku board before the game starts, separated by single spaces. An empty cell is given as 0. The input never describes a board that cannot be filled according to the rules.

Output

Print the final Sudoku board with every empty cell filled, over nine lines, with the 9 digits in each line separated by single spaces.

If there is more than one way to fill the board, print any one of them.

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