Recently, I wrote a Sudoku solver in C++. My program is very hard and was solved in a few seconds. In my opinion, this is slow.
#include <iostream>
#include <conio.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
int tab_in[9][9] = {{0,0,0,0,0,0,0,1,0},
{4,0,0,0,0,0,0,0,0},
{0,2,0,0,0,0,0,0,0},
{0,0,0,0,5,0,4,0,7},
{0,0,8,0,0,0,3,0,0},
{0,0,1,0,9,0,0,0,0},
{3,0,0,4,0,0,2,0,0},
{0,5,0,1,0,0,0,0,0},
{0,0,0,8,0,6,0,0,0}};
int squares[9][9] = {{0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0},
{3,3,3,3,3,3,3,3,3},
{3,3,3,3,3,3,3,3,3},
{3,3,3,3,3,3,3,3,3},
{6,6,6,6,6,6,6,6,6},
{6,6,6,6,6,6,6,6,6},
{6,6,6,6,6,6,6,6,6}};
int tab_out[9][9];
int tab[9][9];
int tab_insert[9][9][10];
int iter=0;
void output_solve();
void load();
bool check(int x, int y, int value);
bool next(int x, int y);
bool solve(int x, int y);
void can_insert();
int main()
{
//load();
for(int i=0; i<9; i++)
{
for(int j=0; j<9; j++)
{
tab_out[i][j]=tab_in[i][j];
}
}
can_insert();
int a = clock();
if(!solve(0, 0))
{
cout<<"This sudoku is unsolvable!"<<endl;
}
else
{
output_solve();
cout<<"\n"<<iter<<endl;
}
int b = clock();
cout<<(b-a)<<"ms"<<endl;
cout<<iter;
getch();
return 0;
}
bool check(int x, int y, int value)
{
for(int i = 0; i < 9; i++)
{
if (value == tab_out[x][i] || value == tab_out[i][y])
{
return false;
}
}
for (int i = squares[x][y]; i <= squares[x][y]+2; i++)
{
for (int j = squares[y][x]; j <= squares[y][x]+2; j++)
{
/*for (int i = (x/3)*3; i <= ((x/3)*3)+2; i++)
{
for (int j = (y/3)*3; j <= ((y/3)*3)+2; j++)
{*/
if (tab_out[i][j] == value)
{
return false;
}
}
}
return true;
}
bool next(int x, int y)
{
if (x == 8 && y == 8) return true;
else if (x == 8) return solve(0, y + 1);
else return solve(x + 1, y);
}
bool solve(int x, int y)
{
if (tab_in[x][y] == 0)
{
int max = tab_insert[x][y][9];
for(int i = 0; i<max; i++)
{
int val = tab_insert[x][y][i];
if (check(x, y, val))
{
tab_out[x][y] = val;
if (next(x, y)) return true;
}
}
iter++;
tab_out[x][y] = 0;
return false;
}
return next(x, y);
}
void load()
{
for(int i=0; i<9; i++)
for(int j=0; j<9; j++)
{
cout<<i+1<<", "<<j+1<<endl;
cin>>tab_in[i][j];
}
}
void output_solve()
{
for(int i=0; i<9; i++)
{ cout<<endl;
if(i%3==0 &&i>0)
{
cout<<"---------------\n";
}
for(int j=0; j<9; j++)
{
if(j%3==0 && j>0) cout<<" | ";
cout<<tab_out[i][j];
}
}
}
void can_insert()
{
for(int i=0; i<9; i++)
{
for(int j=0; j<9; j++)
{
for(int k=0; k<9; k++)
{
tab_insert[i][j][k]=0;
}
}
}
for(int i = 0; i<9; i++)
{
for(int j = 0; j<9; j++)
{
if(tab_in[i][j]==0)
{
int count = 0;
for(int k = 1; k<=9; k++)
{
if(check(i, j, k))
{
tab_insert[i][j][count] = k;
count++;
}
}
tab_insert[i][j][9]=count;
}
}
}
}
How can I optimize this? Where can I find a good Sudoku solver implementation in C/C++?