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
|
#include<iostream>
#include<array>
using namespace std;
typedef array<array<int,9>,9> Grid;
//void backtrack(int& x,int& y);
bool check(Grid& g, int x, int y, int num); //returns false if num isn't allowed at (x,y)
//void input(Grid& g);
//void output(Grid& g);
int main()
{
Grid grid;
int x,y;
for(x=0;x<9;x++)
for(y=0;y<9;y++)
cin>>grid[x][y];//=0;
bool back_flag(true); //SET to true when stepping backwards
for(int r=0;r<81;) //using this loop instead of nested x y loop to make backtracking simpler
{
x = r/9;
y = r%9;
for(int num=1;num<10;num++)
{
if(check(grid,x,y,num))
{
grid[x][y] = num;
back_flag=false;
break;
}
}
if(back_flag)
r--;
else r++;
}
for(int a=0;a<9;a++)
{
for(int b=0;b<9;b++)
cout<<grid[a][b]<<" ";
cout<<endl;
}
return 0;
}
bool check(Grid& g, int x, int y, int num)
{
for(int c=0;c<9;c++)
{
if(g[x][c]==num || g[c][y]==num)
return false;
}
//code below is for checking the local 3x3 grid
int x_init,y_init;
x_init = (x/3)*3;
y_init = (y/3)*3;
for(int x_index = x_init; x_index< x_init+3 ; x_index++)
for(int y_index = y_init; y_index< y_init+3; y_index++)
{
if(g[x_index][y_index]==num)
return false;
}
return true;
}
|