#include <iostream>
using namespace std;
bool isValid(char arr[][9]){
//checking if each row has unique elements
for(int i=0;i<9;i++){
int temp[9] = {0};
for(int j=0;j<9;j++){
if(arr[i][j] != 0)
temp[arr[i][j]-1]++;
}
for(int k=0;k<9;k++){
if(temp[k] > 1) return false;
}
}
//checking if each column has unique elements
for(int i=0;i<9;i++){
int temp[9] = {0};
for(int j=0;j<9;j++){
if(arr[j][i] != 0)
temp[arr[j][i]-1]++;
}
for(int k=0;k<9;k++){
if(temp[k] > 1) return false;
}
}
//checking if each 3x3 have unique elements
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
int temp[9] = {0};
for(int k=i*3;k<(i*3+3);k++){
for(int l=j*3;l<(j*3+3);l++){
if(arr[k][l] != 0)
temp[arr[k][l]]++;
}
}
for(int k=0;k<9;k++){
if(temp[k] > 1) return false;
}
}
}
return true;
}
bool isSolved(char arr[][9]){
for(int i=0;i<9;i++){
for(int j=0;j<9;j++){
if(arr[i][j] == 0) return false;
}
}
return isValid(arr);
}
int values_tried = 0;
bool solved = false;
void solveSudoku(char arr[][9]){
if(!isValid(arr)) return;
if(isSolved(arr)){
for(int i=0;i<9;i++){
for(int j=0;j<9;j++){
cout << (int)arr[i][j] << " ";
}
cout << endl;
}
cout << "This many values tried " << values_tried << endl;
solved = true;
return;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////TRY 1-9 VALUES FOR EACH CELL AND CHECK FOR VALIDITY RECURSIVELY/////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
for(int i=0;i<9;i++){
for(int j=0;j<9;j++){
if(arr[i][j] == 0){
//Trying all values 1-9 for each cell
for(int k=1;k<=9;k++){
values_tried++;
arr[i][j] = k;
solveSudoku(arr);
arr[i][j] = 0;
}
//1-9 didnt work so backing out
return;
}
if(solved) break;
}
if(solved) break;
}
}
int main()
{
char arr[9][9] = {
{8, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 3, 6, 0, 0, 0, 0, 0},
{0, 7, 0, 0, 9, 0, 2, 0, 0},
{0, 5, 0, 0, 0, 7, 0, 0, 0},
{0, 0, 0, 0, 4, 5, 7, 0, 0},
{0, 0, 0, 1, 0, 0, 0, 3, 0},
{0, 0, 1, 0, 0, 0, 0, 6, 8},
{0, 0, 8, 5, 0, 0, 0, 1, 0},
{0, 9, 0, 0, 0, 0, 4, 0, 0}
};
solveSudoku(arr);
cout << "Done" << endl;
return 0;
}
Output:
No comments:
Post a Comment