sudoku-solver/main.cpp

78 lines
1.6 KiB
C++

#include <iostream>
#include<time.h>
// #include<windows.h>
using namespace std;
int start[9][9] =
{
{ 0, 8, 0, 0, 2, 0, 5, 6, 0 },
{ 0, 0, 0, 1, 0, 0, 0, 0, 7 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 5, 0, 0, 9, 0, 4, 0, 8 },
{ 0, 0, 7, 8, 0, 0, 0, 0, 3 },
{ 0, 9, 0, 0, 1, 0, 0, 5, 0 },
{ 2, 0, 4, 0, 0, 0, 8, 0, 0 },
{ 0, 6, 0, 0, 8, 5, 0, 0, 0 },
{ 0, 0, 0, 2, 0, 0, 1, 0, 0 }
};
bool isfine(int feld[9][9], int x, int y)
{
// doppelte Zahl in Zeile oder Spalte?
for (int yi = 0; yi < 9; yi++)
if (yi != y && feld[x][yi] == feld[x][y])
return false;
for (int xi = 0; xi < 9; xi++)
if (xi != x && feld[xi][y] == feld[x][y])
return false;
// Neuner-Kästchen-Test
int x1 = (x / 3) * 3;
int y1 = (y / 3) * 3;
for (int xk = x1; xk < x1 + 3; xk++)
for (int yk = y1; yk < y1 + 3; yk++)
if ((xk!=x || yk!=y) && feld[xk][yk]==feld[x][y])
return false;
return true;
}
bool nextone(int feld[9][9], int x, int y)
{
if (y == 9) { y = 0; x++; };
if (x == 9) return true;
if (feld[x][y] > 0)
{
if (!isfine(feld, x, y)) return false;
return nextone(feld, x, y + 1);
}
else for (feld[x][y] = 1; feld[x][y] <= 9; feld[x][y]++)
{
if (!isfine(feld, x, y)) continue;
if (nextone(feld, x, y + 1)) return true;
}
feld[x][y] = 0;
return false;
}
int main(int argc, char **argv)
{
clock_t time1, tstart;
tstart = clock();
if (nextone(start, 0, 0))
{
for (int x = 0; x < 9; x++)
{
for (int y = 0; y < 9; y++)
cout << start[x][y];
cout << endl;
}
}
else cout << "Nope!" << endl;
time1=clock();
cout<<tstart<<" - " <<time1<<"*"<<CLOCKS_PER_SEC;
return 0;
}