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 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
|
#include<iostream>
using namespace std;
int sudoku[9][9] = { {0} };
int checker[81][2];
int check = 0;
void solvesudoku(int, int);
bool checkrow(int row, int num)
{
for (int column = 0; column < 9; column++)
if (sudoku[row][column] == num)
return false;
return true;
}
bool checkcolumn(int column, int num)
{
for (int row = 0; row < 9; row++)
if (sudoku[row][column] == num)
return false;
return true;
}
bool checkgrid(int row, int column, int num)
{
row = (row / 3) * 3;
column = (column / 3) * 3;
int r, c;
for (r = 0; r < 3; r++)
for (c = 0; c < 3; c++)
if (sudoku[row + r][column + c] == num)
return false;
return true;
}
void navigate(int &row, int &column)
{
if (column < 8)
column++;
else
{
column = 0;
row++;
}
}
void display()
{
int row, column;
cout << "Soloution=" << endl;
for (row = 0; row<9; row++)
{
for (column = 0; column < 9; column++)
{
cout << sudoku[row][column];
if ((column + 1) % 3 == 0)
cout << " ";
}
cout << endl;
if ((row + 1) % 3 == 0)
cout << endl;
}
system("pause");
}
void navigatebackward()
{
check--;
int row = checker[check][0];
int column = checker[check][1];
for (int safe = sudoku[row][column]+1; safe <= 9; safe++)
{
if (checkrow(row, safe) == true && checkcolumn(column, safe) == true && checkgrid(row, column, safe) == true)
{
sudoku[row][column] = safe;
check++;
break;
}
else
{
sudoku[row][column] = 0;
}
}
if (sudoku[row][column] == 0)
navigatebackward();
navigate(row,column);
}
void solvesudoku(int row = 0, int column = 0)
{
while (row < 8)
{
if (sudoku[row][column] != 0)
navigate(row, column);
else
{
checker[check][0] = row;
checker[check][1] = column;
for (int safe = 1; safe <= 9; safe++)
{
if (checkrow(row, safe) == true && checkcolumn(column, safe) == true && checkgrid(row, column, safe) == true)
{
sudoku[row][column] = safe;
check++;
display();
break;
}
}
if (sudoku[row][column] == 0)
{
navigatebackward();
}
}
}
}
void main()
{
solvesudoku();
display();
}
|