#include <iostream>
using namespace std;
int board[9][9];
struct pos {
int x, y;
};
pos find_empty(int bo[9][9])
{
pos result;
result.x = -1;
result.y = -1;
for(auto i = 0; i < 9; i++)
for(auto j = 0; j < 9; j++)
if(bo[i][j] == 0) {
result.x = i;
result.y = j;
return result;
}
return result;
}
bool valid(int bo[9][9], int num, pos position)
{
int i, j;
// check row
for(i = 0; i < 9; i++)
if(bo[position.x][i] == num && position.y != i)
return false;
// check column
for(i = 0; i < 9; i++)
if(bo[i][position.y] == num && position.x != i)
return false;
// check box
int box_x = position.y / 3, box_y = position.x / 3;
for(i = box_y * 3; i < box_y * 3 + 3; i++)
for(j = box_x * 3; j < box_x * 3 + 3; j++)
if(bo[i][j] == num && i != position.x && j != position.y)
return false;
return true;
}
bool backtracking(int bo[9][9])
{
int row, col, i;
pos find = find_empty(bo);
if(find.x == -1)
return true;
row = find.x;
col = find.y;
for(i = 1; i < 10; i++) {
if(valid(bo, i, find)) {
bo[row][col] = i;
if(backtracking(bo))
return true;
bo[row][col] = 0;
}
}
return false;
}
int main(void)
{
int i, j;
for(i = 0; i < 9; i++)
for(j = 0; j < 9; j++)
cin >> board[i][j];
backtracking(board);
for(i = 0; i < 9; i++) {
for(j = 0; j < 9; j++)
cout << board[i][j] << " ";
cout << endl;
}
return 0;
}
I2luY2x1ZGUgPGlvc3RyZWFtPgoKdXNpbmcgbmFtZXNwYWNlIHN0ZDsKCmludCBib2FyZFs5XVs5XTsKCnN0cnVjdCBwb3MgewogICAgaW50IHgsIHk7Cn07Cgpwb3MgZmluZF9lbXB0eShpbnQgYm9bOV1bOV0pCnsKICAgIHBvcyByZXN1bHQ7CiAgICByZXN1bHQueCA9IC0xOwogICAgcmVzdWx0LnkgPSAtMTsKCiAgICBmb3IoYXV0byBpID0gMDsgaSA8IDk7IGkrKykKICAgICAgICBmb3IoYXV0byBqID0gMDsgaiA8IDk7IGorKykKICAgICAgICAgICAgaWYoYm9baV1bal0gPT0gMCkgewogICAgICAgICAgICAgICAgcmVzdWx0LnggPSBpOwogICAgICAgICAgICAgICAgcmVzdWx0LnkgPSBqOwogICAgICAgICAgICAgICAgcmV0dXJuIHJlc3VsdDsKICAgICAgICAgICAgfQoKICAgIHJldHVybiByZXN1bHQ7Cn0KCmJvb2wgdmFsaWQoaW50IGJvWzldWzldLCBpbnQgbnVtLCBwb3MgcG9zaXRpb24pCnsKICAgIGludCBpLCBqOwoKICAgIC8vIGNoZWNrIHJvdwogICAgZm9yKGkgPSAwOyBpIDwgOTsgaSsrKQogICAgICAgIGlmKGJvW3Bvc2l0aW9uLnhdW2ldID09IG51bSAmJiBwb3NpdGlvbi55ICE9IGkpCiAgICAgICAgICAgIHJldHVybiBmYWxzZTsKCiAgICAvLyBjaGVjayBjb2x1bW4KICAgIGZvcihpID0gMDsgaSA8IDk7IGkrKykKICAgICAgICBpZihib1tpXVtwb3NpdGlvbi55XSA9PSBudW0gJiYgcG9zaXRpb24ueCAhPSBpKQogICAgICAgICAgICByZXR1cm4gZmFsc2U7CgogICAgLy8gY2hlY2sgYm94CiAgICBpbnQgYm94X3ggPSBwb3NpdGlvbi55IC8gMywgYm94X3kgPSBwb3NpdGlvbi54IC8gMzsKCiAgICBmb3IoaSA9IGJveF95ICogMzsgaSA8IGJveF95ICogMyArIDM7IGkrKykKICAgICAgICBmb3IoaiA9IGJveF94ICogMzsgaiA8IGJveF94ICogMyArIDM7IGorKykKICAgICAgICAgICAgaWYoYm9baV1bal0gPT0gbnVtICYmIGkgIT0gcG9zaXRpb24ueCAmJiBqICE9IHBvc2l0aW9uLnkpCiAgICAgICAgICAgICAgICByZXR1cm4gZmFsc2U7CgogICAgcmV0dXJuIHRydWU7Cn0KCmJvb2wgYmFja3RyYWNraW5nKGludCBib1s5XVs5XSkKewogICAgaW50IHJvdywgY29sLCBpOwoKICAgIHBvcyBmaW5kID0gZmluZF9lbXB0eShibyk7CgogICAgaWYoZmluZC54ID09IC0xKQogICAgICAgIHJldHVybiB0cnVlOwoKICAgIHJvdyA9IGZpb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