1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
|
#include <iostream>
using namespace std;
bool checkPossible(int grid[][9], int digit, int col, int line) {
for (int i = 0; i < 9; ++i)
if (grid[line][i] == digit)
return false;
for (int i = 0; i < 9; ++i)
if (grid[i][col] == digit)
return false;
int x = col / 3 * 3, y = line / 3 * 3;
for (int i = 0; i < 3; ++i)
for (int j = 0; j < 3; ++j)
if (grid[y + i][x + j] == digit)
return false;
return true;
}
bool solve(int grid[][9], int col = 0, int line = 0) {
while (grid[line][col] != 0) {
if (++col > 8) {
col = 0;
if (++line > 8)
return true;
}
}
for (int digit = 1; digit <= 9; digit++)
if (checkPossible(grid, digit, col, line)) {
grid[line][col] = digit;
if (solve(grid, col, line)) return true;
grid[line][col] = 0;
}
return false;
}
void print(int grid[][9]) {
for (int x = 0; x < 9; x++) {
for (int y = 0; y < 9; y++)
cout << grid[x][y] << ' ';
cout << '\n';
}
}
int main() {
int grid[9][9] = {
{5, 3, 0, 0, 7, 0, 0, 0, 0},
{6, 0, 0, 1, 9, 5, 0, 0, 0},
{0, 9, 8, 0, 0, 0, 0, 6, 0},
{8, 0, 0, 0, 6, 0, 0, 0, 3},
{4, 0, 0, 8, 0, 3, 0, 0, 1},
{7, 0, 0, 0, 2, 0, 0, 0, 6},
{0, 6, 0, 0, 0, 0, 2, 8, 0},
{0, 0, 0, 4, 1, 9, 0, 0, 5},
{0, 0, 0, 0, 8, 0, 0, 7, 9}
};
print(grid);
cout << "------\n";
if (solve(grid))
print(grid);
else
cout << "Unsolvable\n";
}
|